Skip to content

Commit 41d701c

Browse files
authored
Update 3. Longest Substring Without Repeating Characters.go
improve
1 parent 7989003 commit 41d701c

File tree

1 file changed

+13
-10
lines changed

1 file changed

+13
-10
lines changed

leetcode/0003.Longest-Substring-Without-Repeating-Characters/3. Longest Substring Without Repeating Characters.go

+13-10
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,23 @@ func lengthOfLongestSubstring(s string) int {
55
if len(s) == 0 {
66
return 0
77
}
8-
// 扩展 ASCII 码的位图表示(BitSet),共有 256 位
9-
var bitSet [256]uint8
8+
var bitSet [256]bool
109
result, left, right := 0, 0, 0
1110
for left < len(s) {
12-
if right < len(s) && bitSet[s[right]] == 0 {
13-
// 标记对应的 ASCII 码为 1
14-
bitSet[s[right]] = 1
15-
right++
16-
} else {
17-
// 标记对应的 ASCII 码为 0
18-
bitSet[s[left]] = 0
11+
// 右侧字符对应的bitSet被标记true,说明此字符在X位置重复,需要左侧向前移动,直到将X标记为false
12+
if bitSet[s[right]] {
13+
bitSet[s[left]] = false
1914
left++
15+
} else {
16+
bitSet[s[right]] = true
17+
right++
18+
}
19+
if result < right-left {
20+
result = right - left
21+
}
22+
if left+result >= len(s) || right >= len(s) {
23+
break
2024
}
21-
result = max(result, right-left)
2225
}
2326
return result
2427
}

0 commit comments

Comments
 (0)