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 will only appear in one segment. Returns a list representing the length of each string fragment.
Example 1:
输入:S = "ababcbacadefegdehijhklij"
输出:[9,7,8]
解释:
划分结果为 "ababcbaca", "defegde", "hijhklij"。
每个字母最多出现在一个片段中。
像 "ababcbacadefegde", "hijhklij" 的划分是错误的,因为划分的片段数较少。
Example 2:
输入:S = "ffsfvxcvxufe"
输出:[11,1]
Example 3:
输入:S = "aaabbbccac"
输出:[10]
prompt:
S的长度在[1, 500]之间。
S只包含小写字母 'a' 到 'z' 。
Code and ideas
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;
}
};