LeetCode 3. 无重复字符的最长子串
题目描述
思路分析
滑动窗口问题
参考代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
func lengthOfLongestSubstring(s string) int {
left, right := 0, 0
dict := make(map[byte]bool)
res := 0
for right < len(s) {
c := s[right]
for dict[c] {
delete(dict, s[left])
left++
}
res = max(res, right-left+1)
dict[c] = true
right++
}
return res
}
- 时间复杂度:O(n),每个字符最多进出窗口一次。
- 空间复杂度:O(k),其中 k 是字符集大小。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func lengthOfLongestSubstring(s string) int {
left, right := 0, 0
dict := make(map[byte]int)
res := 0
for right < len(s) {
c := s[right]
if index, ok := dict[c]; ok {
left = max(left, index+1)
}
res = max(res, right-left+1)
dict[c] = right
right++
}
return res
}
1
write your code here
CC BY-NC-SA 4.0
许可协议,转载请注明出处!
本博客所有文章除特别声明外,均采用