File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ # 题目
2
+
3
+ 给定一个字符串,找到最长无重复子字符串。
4
+
5
+ ** 举例:**
6
+
7
+ - 给定的“abcabcbb”,答案是“abc”,长度为3。
8
+ - 给定的“bbbbb”,答案是"b",长度为1。
9
+ - 给定的“pwwkew”,答案是"wke",长度为3。注意是最长子字符串,不是最长子序列"pwke"。
10
+
11
+
12
+ # 思路
13
+
14
+ 定义两个变量longest和left,longest用于存储最长子字符串的长度,left存储无重复子串左边的起始位置。
15
+
16
+ 然后创建一个哈希表,遍历整个字符串,如果字符串没有在哈希表中出现,说明没有遇到过该字符,则此时计算最长无重复子串,当哈希表中的值小于left,说明left位置更新了,需要重新计算最长无重复子串。每次在哈希表中将当前字符串对应的赋值加1。
17
+
18
+ # 代码
19
+
20
+ ``` python
21
+ class Solution (object ):
22
+ def lengthOfLongestSubstring (self , s ):
23
+ """
24
+ :type s: str
25
+ :rtype: int
26
+ """
27
+ longest = 0 ; left = 0 ; tmp = {}
28
+ for index, each in enumerate (s):
29
+ if each not in tmp or tmp[each] < left:
30
+ longest = max (longest, index - left + 1 )
31
+ else :
32
+ left = tmp[each]
33
+ tmp[each] = index + 1
34
+ return longest
35
+ ```
You can’t perform that action at this time.
0 commit comments