原题
字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一个字母只会出现在其中的一个片段。返回一个表示每个字符串片段的长度的列表。
示例 1:
输入:S = “ababcbacadefegdehijhklij”
输出:[9,7,8]
解释:
划分结果为 “ababcbaca”, “defegde”, “hijhklij”。
每个字母最多出现在一个片段中。
像 “ababcbacadefegde”, “hijhklij” 的划分是错误的,因为划分的片段数较少。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/partition-labels
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
提示:
S的长度在[1, 500]之间。S只包含小写字母 'a' 到 'z'。
思路
利用 unordered_map 记录每个字母的最远位置,接着遍历整个字符串,维护一个起始距离
l
o
w
low
low 和最远的距离
h
i
g
h
high
high,如果 $i == high $ 说明该区间结束,更新
l
o
w
low
low 。
代码
C++
class Solution {
public:
vector
<int> partitionLabels(string S
) {
int size
= S
.size();
vector
<int> ans
;
unordered_map
<char, int> mp
;
for (int i
= 0; i
< size
; ++i
) {
mp
[S
[i
]] = i
;
}
int low
= 0, high
= 0;
for (int i
= 0; i
< size
; ++i
) {
high
= max(high
, mp
[S
[i
]]);
if (i
== high
) {
ans
.emplace_back(high
- low
+ 1);
low
= i
+ 1;
}
}
return ans
;
}
};
Python
class Solution:
def partitionLabels(self
, S
: str) -> List
[int]:
mp
= {}
ans
= []
for i
in range(0, len(S
)):
mp
[S
[i
]] = i
low
, high
= 0, 0
for i
in range(0, len(S
)):
high
= max(high
, mp
[S
[i
]])
if i
== high
:
ans
.append
(high
- low
+ 1)
low
= i
+ 1
return ans