基本思路
双指针滑动窗口。读取第一个字符,记录下标位置为first,找到该字符最后出现的位置,记录下标为last。遍历[first + 1, last - 1]区间内字符,如果字符最后出现位置在last后面,则更新last。遍历结束后,完成一个子区间划分。
vector<int> partitionLabels(string S) {
vector<int> vec(26, 0);
for (int i = 0; i < S.length(); i++)
{
if (i > vec[S[i] - 'a'])
vec[S[i] - 'a'] = i;
}
vector<int> res;
for (int i = 0; i < S.length();)
{
int last = vec[S[i] - 'a'];
for (int j = i + 1; j < last; j++)
{
if (vec[S[j] - 'a'] > last)
last = vec[S[j] - 'a'];
}
res.push_back(last - i + 1);
i = last + 1;
}
return res;
}