leetcode-03-Longest Substring Without Repeating Characters-python

来源:互联网 发布:淘宝手机卡 编辑:程序博客网 时间:2024/06/17 14:28

找出一串字符中最常不重复的字符个数。
o(n*n)的方法

class Solution(object):    def lengthOfLongestSubstring(self,s):        b=[]        if len(s)==0:            return 0        else:            for index,i in enumerate(s):                a=[]                while( s[index] not in a ):                    a.append(s[index])                    if index<len(s)-1:                        index+=1                     else:                         break                 b.append(len(a))              return max(b)

o(n)的方法。

class Solution(object):    def lengthOfLongestSubstring(self,s):          res = 0          left = 0          d = {}          for index,i in enumerate(s):            if i in d and d[i]>=left:                left=d[i]+1            d[i]=index            res=max(res,index-left+1)        return res        """        :type s: str        :rtype: int        """

遍历字符串一遍,left指向不重复字符串的左边界。d{}中保存的是出现的不重复的字符。如果遍历的下一个字符在d{}中且出现在left右边,则left右移一位,计算这时该字符索引值index-left+1表示到该字符时最大长度。每次取上一次max和这时的index-left+1的max。

0 0