05.Map 案例 滑动区间算法
下面是 Go 语言实现寻找最长不含有重复字符的子串的代码:
滑动区间算法??
package main import "fmt" func longestSubstringWithoutRepeating(s string) string { m := make(map[byte]int) start, maxLength, maxStart := 0, 0, 0 for end := 0; end < len(s); end++ { if lastOccur, ok := m[s[end]]; ok && lastOccur >= start { start = lastOccur + 1 } m[s[end]] = end if end-start+1 > maxLength { maxLength = end - start + 1 maxStart = start } } return s[maxStart : maxStart+maxLength] } func main() { s := "ababcabcbbabcdefgddd" result := longestSubstringWithoutRepeating(s) fmt.Println("The longest substring without repeating characters is:", result) // 输出:abc }