题目:
要把这个字符串s划分为尽可能多的片段,同一字母最多出现在一个片段中。
返回一个表示每个字符串片段的长度的列表。
S
的长度在[1, 500]
之间。S
只包含小写字母'a'
到'z'
思路:
- 先创建一个列表,存放26个字母,起始a-z每个字母的位置都是0:endList = [0]*26
- 遍历字符串,记录每个字母的最远位置,这一步需要循环,代码如下:
for i ,ch in enumerate(s):
endList[ord(ch)-ord('a')]=i#
例如对于字符串‘aba’
i = 0,ch = ‘a’,endList[ord(ch)-ord('a')]=endList[0]=0=i,所以endList列表第一个位置也就是a的位置是0;
i = 1,ch = ‘b’,endList[ord(ch)-ord('a')]=endList[1]=1=i,所以endList列表第二个位置也就是b的位置是1;
i = 2,ch = ‘a’,endList[ord(ch)-ord('a')]=endList[0]=1=i,此时a的最远位置变了,更新endList列表第一个位置也就是a的位置是2;
循环结束,endList=[2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
- 循环完成后,endList列表中26个字母的位置都得到了更新,可用print语句打印出来检查一下
- 接下来创建一个存放长度的列表res,并初始化两个指针,left = most_right =0,然后就循环
- 还是对于字符串里面的每一个字母,找到最远的位置most_right,代码如下:
res = []#待组装的区间
left = most_right =0
for i,ch in enumerate(s):
most_right = max(most_right,endList[ord(ch)-ord('a')])
if i == most_right:
res.append(most_right-left+1)#分割区间的长度
left = most_right+1#继续出发找下一个分割点
return res#返回长度列表
还是以上面‘aba’为例
i = 0,ch = ‘a’,most_right = max(most_right,endList[ord(ch)-ord('a')])=max(0,2)=2
i = 1,ch = ‘b‘’,most_right = max(most_right,endList[ord(ch)-ord('a')])=max(2,1)=2
i = 2,ch = ‘a‘’,most_right = max(most_right,endList[ord(ch)-ord('a')])=max(2,2)=2
此时a的最远位置=当前下标i,也就是走到了a字符的最远位置,于是切开区间,此时计算区间长度most_right-left+1并添加到res中,然后指定新的左边指针,继续循环
完整代码:
class Solution(object):
def partitionLables(self,s):
endList = [0]*26
for i ,ch in enumerate(s):
endList[ord(ch)-ord('a')]=i#不断更新字符的位置,直到最远的那个
# print(ord(ch)-ord('a'))
print(endList)
res = []#待组装的区间
left = most_right =0
for i,ch in enumerate(s):
most_right = max(most_right,endList[ord(ch)-ord('a')])
if i == most_right:
res.append(most_right-left+1)#分割区间的长度
left = most_right+1#继续出发找下一个分割点
return res#返回长度列表
#测试
k = Solution()
l = k.partitionLables("aba")
print(l)
结果输出即测试: