Astring S of lowercase letters is given. We want to partition thisstring into as many parts as possible so that each letter appears in at mostone part, and return a list of integers representing the size of these parts.
Example1:
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 mostone part.
A partition like “ababcbacadefegde”,”hijhklij” is incorrect, because it splits S into less parts.
Note:
1. S will have length in range [1, 500].
2. S will consist of lowercase letters (‘a’ to ‘z’) only.
从这一题开始有些难度了,这题要求你把一个字符串划分为尽可能多的片段,每个片段尽可能包含多的字母
这一题我是使用贪心算法的思想解决的,对于字符串S而言,其最左边的一组一定包含S最左边的第一个字母,然后检索该字母在S中最右边的位置,这里假设为i,如果从S最左边到i之间有一个字母最右边的索引在i右边,那么更新i,继续遍历,直到S最左端到i的字母已经全部遍历了一遍,这个时候0~i就是一个最小的分组,将S切分,对i+1到S最右端继续以上操作
执行该操作直到S切分完毕
class Solution {
public:
int divide(string S, int start, int end,int letterRight[26])
{
int left, right;
left = start;
right = letterRight[S[left] - 'a'];
for (int i = left+1; i <= right; i++)
{
if (letterRight[S[i]-'a'] > right) right = letterRight[S[i] - 'a'];
}
return right - left+1;
}
vector<int> partitionLabels(string S) {
int letterRight[26];
vector<int> result;
for (int i = 0; i < 26; i++)
{
int t = S.find_last_of((char)( i + 'a'));
letterRight[i] = t;
}
int start = 0; int end = S.size(); int tmp;
while (start < end)
{
tmp = divide(S, start, end, letterRight);
result.push_back(tmp);
start += tmp;
}
return result;
}
};