package main import ( "fmt" ) func lengthOfNonRepeatSubStr(s string) int { lastOccured := make(map[rune]int) //记录每个字符最后出现的位置 start := 0 maxLength := 0 for i, ch := range []rune(s) { if lastI, ok := lastOccured[ch]; ok && lastI >= start { start = lastI + 1 } if i-start+1 > maxLength { maxLength = i - start + 1 } lastOccured[ch] = i } return maxLength } func main() { fmt.Println(lengthOfNonRepeatSubStr("abcabcbb")) fmt.Println(lengthOfNonRepeatSubStr("bbbb")) fmt.Println(lengthOfNonRepeatSubStr("pwwkew")) fmt.Println(lengthOfNonRepeatSubStr("我已经不知道屏蔽的标准是什么了,不就是题目耸了点么也屏蔽啊")) }
输出
3
1
3
16
思路:
对于每一个字母x
lastOccured[x]不存在,或者<start -----》无需操作
lastOccured[x] >= start ----->更新start
更新lastOccured[x],更新maxLength