最长的无重复字母的子串

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

 

分析:

第一种方法:

  遍历字符串每个字符,记录以每个字符开头的不含重复字母的子串长度,返回长度最大值。这是一种最笨的方法,运行超时。

第二种方法:

  使用滑窗,滑窗里面存的是以滑窗最左边字符为起始字符的不含重复字符的子串。

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        res = 0
        sub = []
        i = j = 0
        while j < len(s):
            if s[j] not in sub:
                sub.append(s[j])
                if len(sub)>res:
                    res = len(sub)
                j = j+1
            else:
                sub = sub[1:]
        return res

posted on 2017-10-09 14:53  Peyton_Li  阅读(197)  评论(0编辑  收藏  举报

导航