-
解题思路:
对于每个字母"x":
- lastOccurred[x]不存在或者<start => 无需操作
- lastOccurred[x]>=start => 更新start
- 更新lastOccurred[x],maxLength
程序实现
package main
import (
"fmt"
)func lengthOfNonRepeatSubstr(s string) int {
lastOccurred := make(map[byte]int) //记录字串中出现的每个字符在字串中最后出现的位置
maxLength := 0 //记录最长长度
startIndex := 0 //记录字串的起始位置,即在整个字串的下标
for i, ch := range []byte(s) {
if lastLocation, ok := lastOccurred[ch]; ok && lastLocation >= startIndex {
startIndex = lastLocation+1
}
if i-startIndex+1 > maxLength {
maxLength = i-startIndex+1
}
lastOccurred[ch] = i
}
return maxLength
}func main(){
fmt.Println(lengthOfNonRepeatSubstr("abccba"))
fmt.Println(lengthOfNonRepeatSubstr(""))
fmt.Println(lengthOfNonRepeatSubstr("abcde"))
fmt.Println(lengthOfNonRepeatSubstr("a"))
fmt.Println(lengthOfNonRepeatSubstr("aaaa"))
}测试结果:
3
0
5
1
1