diff --git a/leetcode/0003.Longest-Substring-Without-Repeating-Characters/3. Longest Substring Without Repeating Characters.go b/leetcode/0003.Longest-Substring-Without-Repeating-Characters/3. Longest Substring Without Repeating Characters.go index 90ee1e720..672dbdb54 100644 --- a/leetcode/0003.Longest-Substring-Without-Repeating-Characters/3. Longest Substring Without Repeating Characters.go +++ b/leetcode/0003.Longest-Substring-Without-Repeating-Characters/3. Longest Substring Without Repeating Characters.go @@ -5,20 +5,23 @@ func lengthOfLongestSubstring(s string) int { if len(s) == 0 { return 0 } - // 扩展 ASCII 码的位图表示(BitSet),共有 256 位 - var bitSet [256]uint8 + var bitSet [256]bool result, left, right := 0, 0, 0 for left < len(s) { - if right < len(s) && bitSet[s[right]] == 0 { - // 标记对应的 ASCII 码为 1 - bitSet[s[right]] = 1 - right++ - } else { - // 标记对应的 ASCII 码为 0 - bitSet[s[left]] = 0 + // 右侧字符对应的bitSet被标记true,说明此字符在X位置重复,需要左侧向前移动,直到将X标记为false + if bitSet[s[right]] { + bitSet[s[left]] = false left++ + } else { + bitSet[s[right]] = true + right++ + } + if result < right-left { + result = right - left + } + if left+result >= len(s) || right >= len(s) { + break } - result = max(result, right-left) } return result } diff --git a/website/content/ChapterFour/0003.Longest-Substring-Without-Repeating-Characters.md b/website/content/ChapterFour/0003.Longest-Substring-Without-Repeating-Characters.md index fe3f72072..36e027da8 100644 --- a/website/content/ChapterFour/0003.Longest-Substring-Without-Repeating-Characters.md +++ b/website/content/ChapterFour/0003.Longest-Substring-Without-Repeating-Characters.md @@ -60,20 +60,23 @@ func lengthOfLongestSubstring(s string) int { if len(s) == 0 { return 0 } - // 扩展 ASCII 码的位图表示(BitSet),共有 256 位 - var bitSet [256]uint8 + var bitSet [256]bool result, left, right := 0, 0, 0 for left < len(s) { - if right < len(s) && bitSet[s[right]] == 0 { - // 标记对应的 ASCII 码为 1 - bitSet[s[right]] = 1 - right++ - } else { - // 标记对应的 ASCII 码为 0 - bitSet[s[left]] = 0 + // 右侧字符对应的 bitSet 被标记 true,说明此字符在 X 位置重复,需要左侧向前移动,直到将X标记为 false + if bitSet[s[right]] { + bitSet[s[left]] = false left++ + } else { + bitSet[s[right]] = true + right++ + } + if result < right-left { + result = right - left + } + if left+result >= len(s) || right >= len(s) { + break } - result = max(result, right-left) } return result }