1. 程式人生 > >763. Partition Labels(python+cpp)

763. Partition Labels(python+cpp)

題目:

A string S of lowercase letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.
Example 1:

Input: S = "ababcbacadefegdehijhklij" 
Output: [9,7,8]
Explanation: The partition is "ababcbaca", "defegde", "hijhklij". This is a partition so that
 each letter appears in at most one part. A partition like "ababcbacadefegde", "hijhklij" 
 is incorrect, because it splits S into less parts. 

Note:
S will have length in range [1, 500].
S will consist of lowercase letters ('a' to 'z') only.

解釋:
儲存每一個字母在陣列中最後一次出現時的index,在迴圈的過程中更新partitionEndi 指向後一段的第一個字母,i-pre_i就是這一段的長度。
python程式碼:

class Solution(object):
    def partitionLabels(self, S):
        """
        :type S: str
        :rtype: List[int]
        """
set_s=set(S) rfind_dict={} for s in set_s: rfind_dict[s]=S.rfind(s) result=[] i=pre_i=0 while i<len(S): partitionEnd=rfind_dict[S[i]] while i<=partitionEnd: partitionEnd=max(partitionEnd,rfind_dict[
S[i]]) i+=1 result.append(i-pre_i) pre_i=i return result

c++程式碼:

#include<map>
using namespace std;
class Solution {
public:
    vector<int> partitionLabels(string S) {
        map<int,int>rfind;
        for (int i=0;i<S.size();i++)
           rfind[S[i]]=i;
        vector<int> result;
        int i=0;
        int pre_i=i;
        while(i<S.size())
        {
            int partitionEnd=rfind[S[i]];
            while(i<=partitionEnd)
            {
                partitionEnd=max(rfind[S[i]],partitionEnd);
                i+=1;
            }
            result.push_back(i-pre_i);
            pre_i=i;
        }
        return result;
    }
};

總結:
c++如何返回指定元素最後一次出現的位置?
python中,string 有find()index()方法,但是list只有index()方法,而且index()找不到的時候會報錯,find()找不到的時候返回-1,也就是說,雖然index()魯棒性不強,但是更通用。
c++中,string 的函式有find()rfind(),但是<algorithm>中只有find(),也就是說,vector沒有rfind()方法可以用,需要自己手動實現一下。