zoukankan      html  css  js  c++  java
  • leetcode3 Longest Substring Without Repeating Characters

     1 """
     2 Given a string, find the length of the longest substring without repeating characters.
     3 Example 1:
     4 Input: "abcabcbb"
     5 Output: 3
     6 Explanation: The answer is "abc", with the length of 3.
     7 Example 2:
     8 Input: "bbbbb"
     9 Output: 1
    10 Explanation: The answer is "b", with the length of 1.
    11 Example 3:
    12 Input: "pwwkew"
    13 Output: 3
    14 Explanation: The answer is "wke", with the length of 3.
    15              Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
    16 """
    17 """
    18 解法一:双指针法,维护了一个滑动窗口
    19 便于理解,实用性强
    20 """
    21 class Solution1:
    22     def lengthOfLongestSubstring(self, s):
    23         res = 0
    24         l, r = 0, 0
    25         window = [] #双指针法,维护了一个滑动窗口
    26         while l < len(s) and r < len(s):
    27             if s[r] not in window:
    28                 window.append(s[r])
    29                 r += 1
    30                 res = max(res, r - l)
    31             else:
    32                 window.pop(0)
    33                 l += 1
    34         return res
    35 """
    36 解法二:用dict,与leetcode1结合类似
    37 难点在于用一个下标不断更新dict中重复字符的值,
    38 """
    39 class Solution2:
    40     def lengthOfLongestSubstring(self, s):
    41         d = dict()
    42         max_len = 0
    43         start = 0 #作为子串左端标记,一直向右
    44         for i in range(len(s)):
    45             if s[i] in d and d[s[i]] >= start:#!!!!
    46                 start = d[s[i]] + 1 #!!!用start一直更新重复字符的新值
    47             temp = i - start + 1
    48             d[s[i]] = i
    49             max_len = max(max_len, temp)
    50         return max_len
    51 
    52 """
    53 解法三:想用暴力法
    54 Wrong Answer
    55 Input
    56 "abcabcbb"
    57 Output
    58 5
    59 Expected
    60 3
    61 abcbb没符合这种情况
    62 """
    63 class Solution3:
    64     def lengthOfLongestSubstring(self, s: str) -> int:
    65         max_len = 0
    66         for i in range(len(s)):
    67             for j in range(i + 1, len(s)):
    68                 if s[i] == s[j]: #这逻辑有问题
    69                     j -= 1
    70                     break  # 很有用,找到第一个相等的跳出循环
    71             max_len = max(max_len, j - i + 1)
    72         return max_len
  • 相关阅读:
    H3C S3600-28TP-SI配置命令
    笔记本双网卡内外同上
    计算机存储单位与宽带单位
    linux 设置网卡
    linux 挂载命令详解
    vue实现京东动态楼层效果
    js字符与ASCII码互转的方法
    UartAssist串口调试工具
    高字节和低字节是什么意思?
    int16, int32, int64等类型说明
  • 原文地址:https://www.cnblogs.com/yawenw/p/12332710.html
Copyright © 2011-2022 走看看