LeetCode 763 The road to LeetCode that divides the letter interval HERODING

The string S consists of lowercase letters. We need to divide this string into as many segments as possible, and the same letter will only appear in one segment. Returns a list representing the length of each string fragment.

Example 1:

Input: S = "ababcbacadefegdehijhklij"
Output: [9,7,8]
Explanation: The
result of division 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:

S的长度在[1, 500]之间。
S只包含小写字母 'a' 到 'z' 。

Problem-solving ideas:
front-row prompts, the questions have to be read three times! ! !
At first, I was very confused when I saw this topic. Later I found out that this topic is very simple after referring to the solution. The key is the idea. How can you be sure that the letters in the range you cut will not appear in other segments? map! First traverse the string, put the position of each character in the map, that is to say, the information stored in each character in the map is the last position of the character in the string, and then traverse the string again , Use start and end to limit the cutting range, find the position where the characters traversed to i and i are stored in the same position in the map, set it to end, start cutting, and change start to end+1. Why can this be cut? Because when you find the same position in the map where the characters traversed to positions i and i are stored in the map, you will find that all the characters that appear in the range are only in the range, after all, its map[S[i] ]<=i, the code is as follows:

class Solution {
    
    
public:
    vector<int> partitionLabels(string S) {
    
    
        vector<int> result;
        unordered_map<char, int> map; //记录char c 和其最后出现位置的 map
        int start = 0, end = 0;
        for (int i = 0; i < S.size(); i ++) {
    
    
            map[S[i]] = i;
        }
        for (int i = 0; i < S.size(); i ++) {
    
    
            end = max(end, map[S[i]]);
            if (i == end) {
    
    
                result.push_back(end - start + 1);
                start = i + 1;
            }
        }
        return result;
    }
};


/*作者:heroding
链接:https://leetcode-cn.com/problems/partition-labels/solution/zui-qing-xi-de-si-lu-jie-xi-by-heroding/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。*/

Guess you like

Origin blog.csdn.net/HERODING23/article/details/109216678