找到最长子字符串的长度,并且所有字符不重复
题目: 给定一个字符串,找到最长子字符串的长度,要求子字符串中所有字符不重复。 Example: Input: “abcabcbb” Output: 3 Explanation: 满足条件的最长子字符串为 “abc”, 长度为3.
思路: 令max=0,从头遍历字符串,边遍历边计数count,当遍历到与前面存在相同字符处时,比较max与count,若count大于max,则令max等于count,否则max不变;随后重新计数,继续遍历,重复前面操作,直到遍历结束。最后输出最长字符串的长度max。
代码:
def maxL(a): #a为字符串 b=[] count=0 #用于计数 max=0 #存放最大长度 for i in a: #遍历字符串 if i not in b: #判断元素i是否存在b中 b.append(i) count=count+1 else: if max<count: max=count x=b.index(i) if x==0: b.remove(i) #删除值为i的字符 b.append(i) else: del b[0:x+1] #删除索引位置为0-x的字符 b.append(i) count=b.__len__() if max < count: max = count print(max) if __name__==__main__: a=input(Input:) maxL(a)
上一篇:
Java基础知识总结(2021版)