这就是个括号合并问题,
bool cmp(const vector<int>& a, const vector<int>& b){
if (a[0]<b[0]){
return true;
}
else{
return false;
}
}
class Solution {
public:
// "()" problems
vector<int> partitionLabels(string S) {
cout<<S.size()<<endl;
vector<int> temp(2, -1);
vector<vector<int>> cnt(26, temp); // [26, 2] save band
for(int i = 0;i<S.size();i++){
int premin = cnt[int(S[i]-'a')][0];
int premax = cnt[int(S[i]-'a')][1];
if(premin==-1){
premin = i;
premax = i;
}
else{
premin = premin<i?premin:i;
premax = premax>i?premax:i;
}
cnt[int(S[i]-'a')][0] = premin;
cnt[int(S[i]-'a')][1] = premax;
}
// merge pairs
vector<vector<int>> merge; // prerange
for(int i=0;i<26;i++){
if (cnt[i][0]==-1||cnt[i][1]==-1){
continue;
}
vector<int> range = cnt[i]; // judge range in ? merge [has i val]
if (merge.size()==0){
merge.push_back(range);
}
else{ // compare range to all merge
int nojiaoji = true;
for(int j=0;j<merge.size();j++){
vector<int> now = merge[j];
if (now[1]>=range[0]&&now[0]<=range[1]){ // jiaoji
nojiaoji = false;
merge[j][0] = range[0]<now[0]?range[0]:now[0];
merge[j][1] = range[1]>now[1]?range[1]:now[1];
break;
}
}
if (nojiaoji==true){
merge.push_back(range);
}
}
}
// sort merge, and merge again
vector<vector<int>> merge2;
sort(merge.begin(), merge.end(), cmp); // [0, 206], [199, 205]
merge2.push_back(merge[0]); // [0, 206]
for(int i=1;i<merge.size();i++){
vector<int> range = merge2[merge2.size()-1]; // [0, 206]
vector<int> now = merge[i]; // [199, 205]
if (now[1]>=range[0]&&now[0]<=range[1]){ // jiaoji
merge2[merge2.size()-1][0] = range[0]<now[0]?range[0]:now[0];
merge2[merge2.size()-1][1] = range[1]>now[1]?range[1]:now[1];
}
else{
merge2.push_back(now);
}
}
// vector<vector<int>> merge;
vector<int> res;
for(int i=0;i<merge2.size();i++){
//cout<<merge[i][1]<<" "<<merge[i][0]<<endl;
res.push_back(merge2[i][1]-merge2[i][0]+1);
}
return res;
}
};