Likou brushing notes: 763. Divide the letter interval

Subject : 763. Divide the letter interval The
string S consists of lowercase letters. We need to divide this string into as many segments as possible, and the same letter appears in at most one segment. Returns a list representing the length of each string fragment.

Example:

Input: S = "ababcbacadefegdehijhklij"
Output: [9,7,8]
Explanation: The
division result is "ababcbaca", "defegde", "hijhklij".
Each letter appears in at most one segment.
The division of "ababcbacadefegde", "hijhklij" like "ababcbacadefegde" is wrong because there are fewer fragments.

prompt:

The length of S is between [1, 500].
S only contains lowercase letters'a' to'z'.

Ideas

  • Main idea: Greedy + double pointer
  • First: Traverse the code to find the position of the last letter
  • Define start and end to maintain the distance between the same characters
  • Traverse the array again and look for end. When end == i, we can know that all the letters in it are impossible to appear in other places, and they are also the minimum length combination that meets the conditions of the question. And press end-start + 1 into the ans container.
  • Time complexity: O(n); space complexity O(26 + ans container)

Source code

class Solution {
    
    
public:
    vector<int> partitionLabels(string S) {
    
    
        int n = S.size();

        int last[26];
        //保存最后出现的字母的位置
        for(int i = 0; i < n; ++i){
    
    
            last[S[i] - 'a'] = i;
        }

        int start = 0, end = 0;
        vector<int> ans;
        for(int i = 0; i < n; ++i){
    
    
            //找到能符合条件的最小数组
            end = max(end, last[S[i] - 'a']);
            if(i == end){
    
    
                ans.push_back(end - start + 1);
                start = end + 1;
            }
        }
            
        return ans;


    }
};

Guess you like

Origin blog.csdn.net/qq_45914759/article/details/109323348