763. Partition Labels(python+cpp)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/84099761

题目:

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()方法可以用,需要自己手动实现一下。

猜你喜欢

转载自blog.csdn.net/qq_21275321/article/details/84099761