A string S of lowercase letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and 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.
此题的意思是将长字符串分割为多个子串,子串条件为每个子串里的字母均只在本子串出现过,而不会再其他子串出现。
思路
重点在于寻找分割点,也就是每个子串的最后一个字符。从条件来看,每个子串的最后一个字符必定是长字符串里的最后一个子串分割点,且该字符在下一个子串中将不会出现。
所以我们可以用一个哈希表来存储每个字母最后一次出现的位置,如:
a-8
b-6
c-7
...
...
e-15
...
j-23
最后遍历字符串, 维护一个end变量,代表当前字符串结束位置。
代码如下;最后还需要一步是返回每个被分割子串的长度,所以用后一个分割点位置减去前一个分割点位置就是子串长度
class Solution {
public:
vector<int> partitionLabels(string S) {
unordered_map<char,int> last_appear_index_map;
vector<int> partition;
int s_length = S.length();
int end=0;
for(int idx=0;idx<s_length;idx++)
last_appear_index_map[S[idx]] = idx;
for(int start=0; start<s_length;start++){
end = max(end,last_appear_index_map[S[start]]);
if(start==end)
partition.push_back(start+1);
}
if(partition.size()<=1)
return partition;
else{
for(int idx=partition.size()-1; idx>0; idx--)
partition[idx] = partition[idx]-partition[idx-1];
return partition;
}
}
};