赞
踩
思路分析:
- class Solution {
- public:
- // 定义成员函数partitionLabels,接受一个字符串s,返回一个整数向量
- vector<int> partitionLabels(string s) {
- // 获取字符串长度
- int n = s.size();
-
- // 使用unordered_map存储每个字符在字符串中最后出现的位置
- unordered_map<char, int> M;
- for (int i = 0; i < n; i++)
- M[s[i]] = i;
-
- // 初始化指针end和start,用于标记当前分段的结束位置和起始位置
- int end = 0, start = 0;
-
- // 用于存储分段长度的结果向量
- vector<int> result;
-
- // 遍历字符串
- for (int i = 0; i < n; i++) {
- // 更新当前分段的结束位置
- end = max(end, M[s[i]]);
-
- // 如果当前遍历到的位置等于当前分段的结束位置
- if (i == end) {
- // 计算当前分段的长度,并将其加入结果向量
- result.push_back(end - start + 1);
-
- // 更新下一个分段的起始位置
- start = i + 1;
- }
- }
-
- // 返回结果向量
- return result;
- }
- };
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。