- leet_code:链接
- 问题描述:
-
给定又一些小写字符组成的字符串,尽可能多的切分出子串,使得 每个字符在该子串中出现的次数最多,并依次返回各子串的长度。
-
输入输出样例:
- Input: S = “ababcbacadefegdehijhklij”
- Output: [9,7,8]
- 解析: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 .
- 思路:First pass we record the last position for each letter. Second pass we keep the maximum position of the letters we have seen so far. If the pointer exceeds the maximum position, we found the part.
-
c++ 代码:
-
class Solution
{
public:
vector<int> partirionLabels(string S)
{
vector<int> res, pos(26, 0);
for (auto i = 0; i < S.size(); ++i) pos[S[i] - 'a'] = i;
for (auto i = 0, mark = INT_MIN, last_id = 0; i < S.size(); ++i)
{
mark = max(mark, pos[S[i] - 'a']);//note: must assign to argment 'mark'
if (i == mark)
{
res.push_back(i - last_id + 1);
last_id = i + 1;
}
}
return res;
}
};
c++主调函数
#include<iostream>
using namespace std;
#include<string>
#include<vector>
#include<algorithm>
int main(int args, char* argv[])
{
string S = "ababcbacadefegdehijhklij";
Solution solution;
vector<int> res;
res = solution.partirionLabels(S);
for (int i : res)
cout << i << endl;
system("pause");
return 0;
}