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:
1 <= s.length <= 500
s
consists of lowercase English letters.
题目给定一串字符串,将字符串切割成子字符串,使得每个字符最多只能出现在一个子字符串中,并且尽可能多的切割子字符串。问每个子字符串的大小是多少。
思路:用一个数组end记录每个字符最后出现的位置,依次遍历字符串,每遍历过一个字符更新当前子字符串(起始位置start)的最后一个字符位置last,当当前字符即为最后一个字符时,可以切割,更新结果。代码如下:
class Solution {
public:
vector<int> partitionLabels(string s) {
vector<int> end(26, -1);
int count = 0;
for(int i=s.length()-1; i>=0; i--){
if(end[s[i]-'a'] == -1) {
end[s[i]-'a'] = i;
count++;
}
if(count == 26) break;
}
vector<int> res;
int start = 0, last = end[s[0] - 'a'];
for(int i = 0; i < s.length(); i++){
last = max(last, end[s[i]-'a']);
if(last == i){
res.push_back(last - start + 1);
start = i + 1;
}
}
return res;
}
};
time: O(N)
space: O(1) (不算结果的话)