class Solution {
public:
vector<int> partitionLabels(string S) {
vector<int> ans;
if (S.empty()) return ans;
// 依次对数组进行遍历, 先找到相应的数据的最后一个位置, 构成区间, 然后查看区间内的元素, 随时扩充区间.
// 若找到了 就保存下来, 然后继续从下一个上一个区间的最后一个+1的位置继续进行
for (int i = 0; i < S.size();) {
// 最开始确定的区间 [start, end] 这个end可以扩充
int start = i;
// 没有判断这个end是否存在
int end = S.find_last_of(S[start]);
if (end == string::npos) {
end = start;
}
// 当end不存在的时候, 会返回一个很大的数字.
// 在子区间内继续进行扩充
for (int j = start + 1; j <= end; j++) {
string::size_type lastPos = S.find_last_of(S[j]);
// 如果能找到这个字母的最后一个位置
if (lastPos != string::npos && lastPos > end) {
// 这个是最终的end
end = lastPos;
}
}
// 要记录被扩大的区间
ans.push_back(end - start + 1);
// 对i进行更新
i = end + 1;
}
return ans;
}
};
leetcode763. 划分字母区间
最新推荐文章于 2024-08-22 23:35:20 发布