leetcode 763

此题较简单,主要思想就是记录每个字母最后出现的索引,比如首字母最后出现的索引在n,那我们就知道至少第一段长度是要到n的,此外我们遍历前n个字母,如果其中有字母的索引还在后面,那我们就需要更新结束的索引。代码如下:

class Solution:
    def partitionLabels(self, S):
        """
        :type S: str
        :rtype: List[int]
        """
        loc = {}
        
        for i in range(len(S)):
            val = S[i]
            loc[val] = i
        
        length = 0
        result = []
        if len(S) == 0:
            return result
        index = loc[S[0]]
        for i in range(len(S)):
            length = length + 1
            if i == index :
                result.append(length)
                length = 0
                if i != len(S) -1 :
                    index = loc[S[i+1]]
            else :
                if loc[S[i]] > index:
                    index = loc[S[i]]
                
        return result
                
        
        
        
           

猜你喜欢

转载自blog.csdn.net/bengepai/article/details/82114723