8000 Longest Substring Without Repeating Character · slee-code/LeetCode@2fc9fde · GitHub
[go: up one dir, main page]

Skip to content

Commit 2fc9fde

Browse files
committed
Longest Substring Without Repeating Character
1 parent 64937b6 commit 2fc9fde

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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+
```

0 commit comments

Comments
 (0)
0