Longest Substring Without Repeating Characters[medium]

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
        """
        if len(s) > 0:
            list_s = []
            s1 = ''
            for i in range(len(s)):
                for j in range(len(s[i:])):
                    s2 = s[i:]
                    if s2[j] not in s1:
                        s1 += s2[j]
                    else:
                        list_s.append((len(s1), s1))
                        s1 = s2[j]
                list_s.append((len(s1), s1))
                s1 = ''
            list_2 = sorted(list_s)
            return list_2[-1][0]
        return 0

某大神标准答案:

class Solution:
    # @return an integer
    def lengthOfLongestSubstring(self, s):
        start = maxLength = 0
        usedChar = {}
        
        for i in range(len(s)):
            if s[i] in usedChar and start <= usedChar[s[i]]:
                start = usedChar[s[i]] + 1
            else:
                maxLength = max(maxLength, i - start + 1)

            usedChar[s[i]] = i

        return maxLength
        
posted @ 2017-09-19 17:05  Dus  阅读(140)  评论(0编辑  收藏  举报