- Partition Labels
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
Example 1:
Input: S = “ababcbacadefegdehijhklij”
Output: [9,7,8]
Explanation:
The partitions are "ababcbaca", "defegde", "hijhklij".
A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts.
Example 2:
Input: S = “abcab”
Output: [5]
Explanation:
We can not split it.
Notice
1.S will have length in range [1, 500].
2.S will consist of lowercase letters (‘a’ to ‘z’) only.
解法1:
我的思路跟网上的标准答案差不多。首先是找出每个字符的最后出现的位置,然后从头开始扫描,每次把posEnd更新到posEnd和当前字符最后出现的位置的最大值。如果p1==posEnd,说明当前这段已经没有新的字符出现了,可以单独作为一段。
class Solution {
public:
/**
* @param S: a string
* @return: a list of integers representing the size of these parts
*/
vector<int> partitionLabels(string &S) {
int len = S.size();
vector<int> lastPos(26, 0);
int p1 = 0, p2 = 0;
for (int i = 0; i < len; ++i) {
lastPos[S[i] - 'a'] = i;
}
vector<int> result;
int posStart = 0, posEnd = 0;
while(p1 < len && p2 < len) {
p2 = lastPos[S[p1] - 'a'];
posEnd = max(posEnd, p2);
if (p1 == posEnd) {
result.push_back(posEnd - posStart + 1);
posStart = posEnd + 1;
}
p1++;
}
return result;
}
};
代码更新在
https://github.com/luqian2017/Algorithm