leetcode3 Longest Substring Without Repeating Characters
Posted yawenw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 本题用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的主要内容,如果未能解决你的问题,请参考以下文章
leetcode3. Longest Substring Without Repeating Characters
Leetcode3---Longest Substring Without Repeating Characters
leetcode3 Longest Substring Without Repeating Characters
LeetCode 3. Longest Substring Without Repeating Characters
3. 没有重复字母的最长子串 [leetcode 3: Longest Substring Without Repeating Characters]
3. 没有重复字母的最长子串 [leetcode 3: Longest Substring Without Repeating Characters]