Longest Substring Without Repeating Characters

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.

题目的意思很明显,让求最长子串。开始想到用滑动区间,但是我用了列表(list),Python学了这么久上来就用列表还挺汗颜的。既然提到了没有重复数字,那就应该想到用集合。可以暴力求解,判断任意一个子串里是否有重复的数字,然后不断更新最大子串长度。代码如下:

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        ans = 0
        for i in range(len(s)):
            for j in range(i+1, len(s)+1):
                if self.allUnique(s, i, j):
                    ans = max(ans, j-i)
        return ans

    def allUnique(self, s, start, end):
        uni = set()
        for i in range(start, end):
            if s[i] in uni:
                return False
            else:
                uni.add(s[i])
        return True

暴力法时间超出限制。因为我们做了很多重复的判断,修改代码如下:

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        res = set()
        i = 0
        j = 0
        ans = 0
        while i < len(s) and j < len(s):
            if s[j] not in res:
                res.add(s[j])
                j += 1
                ans = max(ans, j-i)
            else:
                res.remove(s[i])
                i += 1
        return ans

 

posted @ 2017-08-27 22:06  Nicotine1026  阅读(146)  评论(0编辑  收藏  举报