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
}

 

posted @ 2024-07-09 02:00  JJJhr  阅读(5)  评论(0编辑  收藏  举报