golang 計算最長不重複字串長度

毛仔發表於2019-03-13
package  main

import "fmt"

func lengthOfNonRepeatingSubStr(s string) int{
    record := make(map[byte]int)
    start := 0
    maxLength := 0

    for i, ch := range []byte(s) {

        lastI, ok := record[ch]
        if ok && lastI >= start {
            start = lastI + 1
        }

        if i - start + 1 > maxLength {
            maxLength = i - start + 1
        }

        record[ch] = i
    }

    return maxLength

}

func main() {
    fmt.Println(
        lengthOfNonRepeatingSubStr("abcabcbb"), // 3
        lengthOfNonRepeatingSubStr("bbbbbbbb"), // 1
        lengthOfNonRepeatingSubStr("pwwkew"), // 3
    )
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章