763划分字母区间

from typing import List
# 这道题使用双指针的方法写的。
# 两个指针定义开头和结束,首先找到尾指针和头指针相同的字符。(注意要从后边寻找)
# 然后判断两个指针中间的字符在字符串中是否存在其他的相同字符。
class Solution:
def partitionLabels(self, S: str) -> List[int]:
# 定义列表,用来存放分段的字符串长度
self.str_list = []
# 字符串为空返回空列表
if len(S) == 0:return []
# 先定义两个指针
index1,index2 = 0,len(S) - 1
# 当寻找到分段字符串的长度等于字符串长度时就退出循环
while sum(self.str_list) < len(S):
# 首先找到尾指针和头指针相同的字符
while S[index2] != S[index1]:
index2 -= 1
index = index1
# 然后判断index1 - index2 中间的字符在S中的其他地方有没有出现
while index1 != index2:
# 如果有出现,就接着从后边遍历尾指针,找到那个和当前的字符相同的
if S[index1] in S[index2:]:
index2 = len(S) - 1
while S[index2] != S[index1]:
index2 -= 1
index1 += 1
# 将分段的字符串长度添加进去列表。
self.str_list.append(index2 - index + 1)
# 改变idnex1和index2的值,重新循环
index1,index2 = index2 + 1,len(S) - 1
return self.str_list


A = Solution()
print(A.partitionLabels("ababcbacadefegdehijhklij"))
print(A.partitionLabels("aebbedaddc"))
posted @ 2020-08-09 19:07  月为暮  阅读(223)  评论(0编辑  收藏  举报