• 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
            
    
  • 相关阅读:
    第十二章 圆周率的计算问题分析
    第十一章:random库概述
    【模板】分治 FFT
    [PKUWC2018]Slay the Spire
    [PKUWC2018]随机算法
    [PKUWC2018]Minimax
    线段树合并初探
    平衡树初探
    Luogu P1613 跑路 题解报告
    CH138 兔子和兔子 题解报告
  • 原文地址:https://www.cnblogs.com/wspblog/p/7552781.html
Copyright © 2020-2023  润新知