zoukankan      html  css  js  c++  java
  • 763. Partition Labels

    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:

    1. S will have length in range [1, 500].
    2. S will consist of lowercase letters ('a' to 'z') only.
    class Solution(object):
        def partitionLabels(self, S):
            """
            :type S: str
            :rtype: List[int]
            """
            
            #记录每个元素最后一次出现的位置
            d = {c:i for i,c in enumerate(S)}
            
            res = []
            start=end = 0
            
            for i,c in enumerate(S):
                #设置尾部
                end = max(end, d[c])
                #当区间里所有元素都遍历过,设置下一个头部
                if i == end:
                    res.append(end-start+1)
                    start = i+1
                    
            return res
  • 相关阅读:
    codevs 1031 质数环
    codevs 1005 生日礼物
    codevs 1004 四子连棋
    codevs 2292 图灵机游戏
    1439 统计素数个数
    1675 大质数 2
    codevs 1462 素数和
    [NOIp2012提高组]借教室
    [NOIp2007提高组]矩阵取数游戏
    [TJOI2017]城市
  • 原文地址:https://www.cnblogs.com/boluo007/p/12593528.html
Copyright © 2011-2022 走看看