首页 > 其他 > 详细

763划分字母区间

时间:2020-08-09 20:13:37      阅读:104      评论:0      收藏:0      [点我收藏+]
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"))

763划分字母区间

原文:https://www.cnblogs.com/cong12586/p/13463978.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!