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.
Note:
S will have length in range [1, 500].
S will consist of lowercase letters (‘a’ to ‘z’) only.
class Solution {
public:
vector<int> partitionLabels(string S) {
map<char,int>hash;
vector<int>ans;
vector<char>sub;
int vis[26],i=0,pre=-1;
for(i=0;i<S.size();i++) hash[S[i]]++;
for(i=0;i<S.size();i++)
{
char cur=S[i];
hash[cur]--;
if(vis[cur-'a']!=1)
{
vis[cur-'a']=true;
sub.push_back(cur);
}
if(hash[cur]==0)
{
int j=0;
for(;j<sub.size();j++)
if(hash[sub[j]]!=0)
break;
if(j==sub.size())
{
ans.push_back(i-pre);
sub.clear();
pre=i;
}
}
}
return ans;
}
};