zoukankan      html  css  js  c++  java
  • 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
            
    
  • 相关阅读:
    【ZJ选讲·压缩】
    【ZJ选讲·调整】
    【ZJ选讲·钻石游戏】
    【ZJ选讲·BZOJ 5073】
    【ZJ选讲·BZOJ 5071】
    【模拟赛·polyline】
    【BZOJ 2744 朋友圈】
    【BZOJ 2241 打地鼠】
    【CF edu 30 D. Merge Sort】
    【CF edu 30 C. Strange Game On Matrix】
  • 原文地址:https://www.cnblogs.com/wspblog/p/7552781.html
Copyright © 2011-2022 走看看