使用go语言寻找最长不含有重复字符的字串,统计数量

go语言Map例题(寻找最长不含有重复字符的字串 )

要求 a := abcdabc 那么得出统计说是4,实现下方代码
解题思路

  1. lastOccurred[x]不存在,或者无需操作
  2. lastOccurred[x] >= start -> 更新start
  3. 更新lastOccurred[x],更新maxLength
func lengthOfNonRepeatingSubstr(s string) int {
	lastOccurred := make(map[rune]int)
	start := 0
	maxLength := 0

	for i, ch := range []rune(s) {
		if lastI, ok := lastOccurred[ch]; ok && lastI >= start {
			start = lastI + 1
		}
		if i-start+1 > maxLength {
			maxLength = i - start + 1
		}
		lastOccurred[ch] = i
	}
	return maxLength
}

fmt.Println(lengthOfNonRepeatingSubstr("abc")) // 3

你可能感兴趣的:(go,go)