题目
https://leetcode.com/problems/partition-labels/
You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part.
Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s.
Return a list of integers representing the size of these parts.
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.
分析
同一个字母不能在一个分区中出现两次,那么只考虑最先和最后的这个字母。每一对字母表示了字符串中的一个连续区域。每个区域分三种情况:
- 完全被某一其他区域包围 如
abba
:这种情况下被包围的区就可以不考虑了 - 和其他区域相交 ,如
abcabc
三个区域相互嵌套:有重叠的区域联合成一个更大的区域,合成区域也符合三种情况的判定标准 - 不被任一区域包围,且不相交:这是一个完整的分区
我们只需要确定所有的第三种区域即可。
算法流程
- 遍历一遍,找到所有字母最左边和最右边出现的下标,为初始分区
- 将初始分区按照左下标排序
- 将“合并分区”初始化为排序第一个分区
- 遍历所有初始分区:
(a) 如果下一个分区的左下标大于当前合并分区的右下标,那么当前“合并分区”结算,并更新为新分区的左右下标
(b) 否则,如果下一个分区的右下标,大于当前合并分区的右下标,则更新当前“合并分区”的右下标,相当于扩展“合并分区”
代码
class Solution {
public:
vector<int> partitionLabels(string s) {
vector<int> result;
int left[128],right[128];
bool appeared[128]={false};
int len = s.size();
for (int i=0;i<len;i++){
if (!appeared[s[i]])
{
appeared[s[i]] = true;
left[s[i]] = i;
}
right[s[i]] = i;
}
class Partition{
public:
int l,r;
Partition(int l_,int r_){
l = l_;
r = r_;
}
bool operator<(const Partition & x) const{
return l<x.l;
}
};
vector<Partition> p;
for (char i='a';i<='z';i++)
if (appeared[i])
p.push_back(Partition(left[i],right[i]));
sort(p.begin(),p.end());
int l=-1,r;
for (vector<Partition>::iterator iter = p.begin();iter!=p.end();iter++){
if (l==-1){
l = iter->l;
r = iter->r;
}
else
if (iter->l>r){
result.push_back(r-l+1);
l = iter->l;
r = iter->r;
}
else if (iter->r>r)
r = iter->r;
}
result.push_back(r-l+1);
return result;
}
};