Leetcode:3-Longest Substring Without Repeating Characters

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode:3-Longest Substring Without Repeating Characters相关的知识,希望对你有一定的参考价值。

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.

 

题意:求一个字符串中最长的不含重复字符的子串。

思路:利用哈希表,对遍历的字符进行记录。但是需要注意:检测到重复字符时,要从该字符第一次出现的后一个字符处重新计数,否则会出错。第一次做的时候遇到重复字符,从第二次出现的位置重新计数,这样就把字符串切断了,比如字符串‘dvdf’,正确答案是‘vdf’,3个,从重复字符第一次位置的后一个字符再重新开始,但是若按我第一次做的方法从第二次出现的位置重新计数,就是‘df’了。

 1 class Solution:
 2     def lengthOfLongestSubstring(self,s):
 3         start = 0
 4         maxlen = 0
 5         dict = {}
 6         for i in range(len(s)):
 7             dict[s[i]] = -1
 8         for i in range(len(s)):
 9             if dict[s[i]] != -1:  #检测到重复字符时
10                 while start <= dict[s[i]]:
11                     dict[s[start]] = -1  #第一个重复字符前的字符清除标记
12                     start += 1  #从第一个重复字符的下一个字符开始计算,设其为start
13             if i - start + 1 > maxlen: maxlen = i - start + 1
14             dict[s[i]] = i  #扫描过的数字及时标记
15         return maxlen
16 
17 if __name__==__main__:
18     s=dvdf
19     solution=Solution()
20     print(solution.lengthOfLongestSubstring(s))

 

以上是关于Leetcode:3-Longest Substring Without Repeating Characters的主要内容,如果未能解决你的问题,请参考以下文章

3. 没有重复字母的最长子串 [leetcode 3: Longest Substring Without Repeating Characters]

3. 没有重复字母的最长子串 [leetcode 3: Longest Substring Without Repeating Characters]

leetcode 3. Longest Substring Without Repeating Characters (Python版)

LeetCode - 3 - Longest Substring Without Repeating Characters

[LeetCode]3. Longest Substring Without Repeating Characters

[leetcode]3-Longest Substring Without Repeating Characters