func BenchmarkSubstr(b *testing.B) {
s := "黑化肥挥发发挥灰化肥挥发发黑会飞话"
maxLength := 8
for i := 0; i < 11; i++ {
s = s + s
}
//b.Logf("len(s) = %d", len(s))
b.ResetTimer()
// b.N = 4000000
for i := 0; i < b.N; i++ {
actual := nonRepeatingStr(s)
if actual != maxLength {
b.Errorf("got %d for input %s; expected %d", actual, s, maxLength)
}
}
}
package main
import (
"fmt"
)
var lastOccurred = make([]int, 0xffff) // 空间换时间 65535; lastOccurred[0x65]
func nonRepeatingStr(s string) int {
// 每个字母最后出现的位置
//lastOccurred := make(map[rune]int)
for i := range lastOccurred {
lastOccurred[i] = -1
}
// 子字符串开始的位置
start := 0
// 子字符串的长度
maxLength := 0
for i, ch := range []rune(s) {
// 当前字符,从开始位置,如果出现过;开始位置从当前字符出现过的位置+1
//if lastI, ok := lastOccurred[ch]; ok && lastI >= start {
if lastI := lastOccurred[ch]; lastI != -1 && lastI >= start {
start = lastOccurred[ch] + 1
}
if i-start+1 > maxLength {
maxLength = i - start + 1
}
lastOccurred[ch] = i
}
return maxLength
}