#include<iostream>
#include<stack>
#include <vector>
#include<string>
#include<algorithm>
#include<unordered_map>
#include <climits>
#include<queue>
#include<unordered_set>
#include<cctype>
#include <sstream>
#include<set>
using namespace std;
#define maxsize 100
//划分字母区间:
//给定一个只包含小写字母的字符串 S,将字符串 S 划分为尽可能多的部分,
// 使得每个字母最多只出现在一个部分中,并返回每个部分的长度。
// 例如,给定字符串 S = "ababcbacadefegdehijhklij",
// 划分后的部分为["ababcbaca", "defegde", "hijhklij"]。
vector<int> partitionLabels(string s) {
vector<int> partitions;
unordered_map<char, int> lastIndex; // 记录每个字符最后出现的位置
for (int i = 0; i < s.size(); ++i) {
lastIndex[s[i]] = i;
}
int start = 0;
int end = 0;
for (int i = 0; i < s.size(); ++i) {
end = max(end, lastIndex[s[i]]); // 更新当前划分范围的结束位置
if (i == end) { // 如果当前位置是当前划分范围的结束位置
partitions.push_back(end - start + 1); // 添加当前划分范围的长度到结果中
start = end + 1; // 更新下一个划分范围的起始位置
}
}
return partitions;
}
int main() {
string s = "ababcbacadefegdehijhklij";
vector<int> result = partitionLabels(s);
cout << "划分后的部分长度为:";
for (int len : result) {
cout << " " << len;
}
cout << endl;
return 0;
}