763. Partition Labels
不知道是该叫它sliding window
还是三指针
...
先设置双指针l,r
,从头开始遍历:
将右指针
r
直接移动到目前遇到的字符所出现的最后一个位置(最右位置)然后对左右指针之间的字符进行遍历(
i
指针),根据遇到的字符去扩展目前i
遍历的右边界(即r
,只扩大,不回缩),直到i
和r
相交(即l
与r
之间的所有字符都不会再在右侧出现),记录一下当前长度为一个结果。将
l
指针移到r
的右边,开始下一个对i
的遍历。
class Solution:
def partitionLabels(self, S: str) -> List[int]:
count = collections.Counter(S)
rightMost = {ch: S.rindex(ch) for ch in count.keys()}
res = []
l, r = 0, 0
## step 1
while l < len(S) and r < len(S):
r = rightMost[S[l]]
## step 2
i = l
while i != r:
r = max(r, rightMost[S[i]])
i += 1
res.append(r-l+1)
## step 3
l = r+1
return res
Last updated
Was this helpful?