原题链接:Leetcode 763. Partition Labels
You are given a string s
. We want to partition the string into as many parts as possible so that each letter appears in at most one part.
Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s.
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.
Example 2:
Input: s = "eccbbbbdec"
Output: [10]
Constraints:
首先遍历一遍字符串,记录下每个字母的最后出现下标
再遍历字符串,用于找到进行划分的下标end。
end每次用max(end,list[s[i]])
进行维护,当出现i = end时,说明在他之前的元素在i之后就都不会再出现了,此时就可以进行划分了
class Solution {
public:
vector<int> partitionLabels(string s) {
// 记录字母最后一次出现的下标
int last[26];
int length = s.size();
// 更新最后出现的下标
for (int i = 0; i < length; i++) {
last[s[i] - 'a'] = i;
}
vector<int> ans;
int start = 0, end = 0;
for (int i = 0; i < length; i++) {
// end是当前区间的结束下标
end = max(end, last[s[i] - 'a']);
// 说明之前遍历到的字母都再此时结束, 后面不会再出现了
if (i == end) {
ans.push_back(end - start + 1);
start = end + 1;
}
}
return ans;
}
};