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.

    Approach #1: C++.

    class Solution {
    public:
        vector<int> partitionLabels(string S) {
            int len = S.length();
            int curLen = 0;
            vector<int> ans;
            
            for (int i = 0; i < len; ++i) {
                curLen = helper(S, i);
                for (int j = i+1; j < curLen; ++j) {
                    curLen = max(curLen, helper(S, j));
                }
                
                ans.push_back(curLen-i+1);
                i = curLen;
            }
            
            return ans;
        }
        
        int helper(string S, int index) {
            int curLen = index;
            int len = S.length();
            int temp;
            while (index >= 0) {
                curLen = index;
                index = S.find(S[curLen], curLen+1);
            }
            
            return curLen;
        }
    };
    

      

    Analysis:

    I use helper function to find the last index of current character. In the partitionLabels function we traversing the string and find the min interval.

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    「SOL」开关(LOJ)
    「SOL」星际迷航(LOJ)
    「NOTE」概率生成函数
    「SOL」谢特(LOJ)
    「SOL」重建计划(BZOJ)
    「SOL」Tug of War(洛谷)
    「SOL」同余方程(LOJ)
    「SOL」Bad Cryptography(Codeforces)
    「SOL」小A与两位神仙(洛谷)
    「SOL」Social Distance(AtCoder)
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10252376.html
Copyright © 2011-2022 走看看