Leetcode.763. 划分字母区间

763. 划分字母区间

字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一个字母只会出现在其中的一个片段。返回一个表示每个字符串片段的长度的列表。

示例 1:

输入:S = "ababcbacadefegdehijhklij"
输出:[9,7,8]
解释:
划分结果为 "ababcbaca", "defegde", "hijhklij"。
每个字母最多出现在一个片段中。
像 "ababcbacadefegde", "hijhklij" 的划分是错误的,因为划分的片段数较少。

示例 2:

输入:S = "ffsfvxcvxufe"
输出:[11,1]

示例 3:

输入:S = "aaabbbccac"
输出:[10]

提示:

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

代码与思路

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;
    }
};

其它

合并区间

猜你喜欢

转载自blog.csdn.net/e891377/article/details/109218502