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.
method:贪心
用个数组当哈希表,存储每个字母最后出现的位置end
,遍历数组的时候,end
要根据当前元素最后出现的位置取较大值,当遍历到end
的时候这一段才结束,没有元素的最后位置超出end
了
vector<int> partitionLabels(string s) {
int hash[26];
for (int i = 0; i < s.size(); i++) {
hash[s[i] - 'a'] = i;
}
vector<int> res;
int start = 0;
int end = 0;
for (int i = 0; i < s.size(); i++) {
end = max(end, hash[s[i] - 'a']);
if (i == end) {
res.push_back(end - start + 1);
start = end + 1;
}
}
return res;
}