码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode3 Longest Substring Without Repeating Characters

时间:2020-02-19 21:02:41      阅读:53      评论:0      收藏:0      [点我收藏+]

标签:bsp   暴力   example   解法   repeat   expec   eating   tput   out   

 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 本题用dict,与leetcode1结合类似
19 难点在于用一个下标不断更新dict中重复字符的值,
20 """
21 class Solution1:
22     def lengthOfLongestSubstring(self, s):
23         d = dict()
24         max_len = 0
25         start = 0 #作为子串左端标记,一直向右
26         for i in range(len(s)):
27             if s[i] in d and d[s[i]] >= start:#!!!!
28                 start = d[s[i]] + 1 #!!!用start一直更新重复字符的新值
29             temp = i - start + 1
30             d[s[i]] = i
31             max_len = max(max_len, temp)
32         return max_len
33 
34 """
35 解法二:想用暴力法
36 Wrong Answer
37 Input
38 "abcabcbb"
39 Output
40 5
41 Expected
42 3
43 abcbb没符合这种情况
44 """
45 class Solution2:
46     def lengthOfLongestSubstring(self, s: str) -> int:
47         max_len = 0
48         for i in range(len(s)):
49             for j in range(i + 1, len(s)):
50                 if s[i] == s[j]: #这逻辑有问题
51                     j -= 1
52                     break  # 很有用,找到第一个相等的跳出循环
53             max_len = max(max_len, j - i + 1)
54         return max_len

 

leetcode3 Longest Substring Without Repeating Characters

标签:bsp   暴力   example   解法   repeat   expec   eating   tput   out   

原文地址:https://www.cnblogs.com/yawenw/p/12332710.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!