Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 88d9ea8

Browse files
🐱(string): 3. 无重复字符的最长子串
1 parent bf47953 commit 88d9ea8

File tree

1 file changed

+50
-1
lines changed

1 file changed

+50
-1
lines changed

‎docs/data-structure/string/README.md‎

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,34 @@ if __name__ == '__main__':
7676

7777
[原题链接](https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/solution/)
7878

79-
### 思路
79+
### 解一:暴力求解
80+
81+
```python
82+
class Solution:
83+
def lengthOfLongestSubstring(self, s: str) -> int:
84+
length = len(s)
85+
ans = 0
86+
for i in range(length):
87+
tmp = 1
88+
nums = dict()
89+
nums[s[i]] = True
90+
for j in range(i + 1, length):
91+
c = s[j]
92+
if c in nums:
93+
# 已经存在
94+
break
95+
else:
96+
# 不存在,继续
97+
tmp += 1
98+
nums[c] = True
99+
ans = max(ans, tmp)
100+
return ans
101+
```
102+
103+
- 时间复杂度:`O(n^2)`
104+
- 空间复杂度:`O(m)`
105+
106+
### 解二
80107

81108
- 用 hash 记录每个字符出现的位置
82109
- 当前字符:
@@ -108,6 +135,28 @@ class Solution(object):
108135
return max_length
109136
```
110137

138+
2020年05月02日 复盘:
139+
140+
```python
141+
class Solution:
142+
def lengthOfLongestSubstring(self, s: str) -> int:
143+
ans = 0
144+
# 滑动窗口,左侧:start,右侧:i
145+
start = 0
146+
length = len(s)
147+
# 记录字符所在下标
148+
nums = dict()
149+
for i in range(length):
150+
cur_c = s[i]
151+
# print(start)
152+
if cur_c in nums:
153+
if nums[cur_c] >= start:
154+
start = nums[cur_c] + 1
155+
# 替换字符所在位置
156+
nums[cur_c] = i
157+
ans = max(ans, i - start + 1)
158+
return ans
159+
```
111160

112161
## 6. Z 字形变换
113162

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /