- 49. 字母异位词分组(Medium)
- 438. 找到字符串中所有字母异位词(Medium)/ 839. (交换2个字母)相似字符串组(Hard)/ 567. s2 是否包含 s1 的排列(M) / 字母分组(滑窗)问题!!!
- 题解
class Solution:
# 贪心
def partitionLabels(self, s: str) -> List[int]:
# 得到每个字母最后一次出现的下标位置
last = [0] * 26
for i, ch in enumerate(s):
last[ord(ch) - ord("a")] = i
res = []
start = end = 0
for i, ch in enumerate(s):
# 对于每个访问到的字母ch,更新得到当前字母的最后一次出现的下标位置end
end = max(end, last[ord(ch) - ord("a")])
# 若当前片段遍历完毕
if i == end:
res.append(end - start + 1) # 计算长度
start = end + 1 # 继续寻找下一个片段,则更新start
return res