fix/3: clean up code

This commit is contained in:
novahe
2021-05-12 00:45:49 +08:00
parent 012999a33b
commit 3c1176be43
2 changed files with 53 additions and 36 deletions

View File

@ -26,25 +26,35 @@ func lengthOfLongestSubstring(s string) int {
return result return result
} }
// 解法二 滑动窗口 // 解法二 滑动窗口-数组桶
func lengthOfLongestSubstring_(s string) int { func lengthOfLongestSubstring1(s string) int {
if len(s) == 0 { right, left, res := 0, 0, 0
return 0 var indexes [256]int
}
var freq [256]int
result, left, right := 0, 0, -1
for left < len(s) { for left < len(s) {
if right+1 < len(s) && freq[s[right+1]-'a'] == 0 { tmp := indexes[s[left]-'a']
freq[s[right+1]-'a']++ if tmp >= right {
right++ right = tmp + 1
} else {
freq[s[left]-'a']--
left++
} }
result = max(result, right-left+1) indexes[s[left]-'a'] = left
left++
res = max(res, left-right)
} }
return result return res
}
// 解法二 滑动窗口-哈希桶
func lengthOfLongestSubstring2(s string) int {
right, left, res := 0, 0, 0
indexes := make(map[byte]int, len(s))
for left < len(s) {
if idx, ok := indexes[s[left]]; ok && idx >= right {
right = idx + 1
}
indexes[s[left]] = left
left++
res = max(res, left-right)
}
return res
} }
func max(a int, b int) int { func max(a int, b int) int {

View File

@ -52,7 +52,6 @@ Explanation: The answer is "wke", with the length of 3.
## 代码 ## 代码
```go ```go
package leetcode package leetcode
// 解法一 位图 // 解法一 位图
@ -63,7 +62,7 @@ func lengthOfLongestSubstring(s string) int {
var bitSet [256]bool var bitSet [256]bool
result, left, right := 0, 0, 0 result, left, right := 0, 0, 0
for left < len(s) { for left < len(s) {
// 右侧字符对应的 bitSet 被标记 true说明此字符在 X 位置重复需要左侧向前移动直到将X标记为 false // 右侧字符对应的bitSet被标记true说明此字符在X位置重复需要左侧向前移动直到将X标记为false
if bitSet[s[right]] { if bitSet[s[right]] {
bitSet[s[left]] = false bitSet[s[left]] = false
left++ left++
@ -81,25 +80,35 @@ func lengthOfLongestSubstring(s string) int {
return result return result
} }
// 解法二 滑动窗口 // 解法二 滑动窗口-数组桶
func lengthOfLongestSubstring_(s string) int { func lengthOfLongestSubstring1(s string) int {
if len(s) == 0 { right, left, res := 0, 0, 0
return 0 var indexes [256]int
}
var freq [256]int
result, left, right := 0, 0, -1
for left < len(s) { for left < len(s) {
if right+1 < len(s) && freq[s[right+1]-'a'] == 0 { tmp := indexes[s[left]-'a']
freq[s[right+1]-'a']++ if tmp >= right {
right++ right = tmp + 1
} else {
freq[s[left]-'a']--
left++
} }
result = max(result, right-left+1) indexes[s[left]-'a'] = left
left++
res = max(res, left-right)
} }
return result return res
}
// 解法二 滑动窗口-哈希桶
func lengthOfLongestSubstring2(s string) int {
right, left, res := 0, 0, 0
indexes := make(map[byte]int, len(s))
for left < len(s) {
if idx, ok := indexes[s[left]]; ok && idx >= right {
right = idx + 1
}
indexes[s[left]] = left
left++
res = max(res, left-right)
}
return res
} }
func max(a int, b int) int { func max(a int, b int) int {
@ -108,8 +117,6 @@ func max(a int, b int) int {
} }
return b return b
} }
``` ```