论:如何找出一个字符串种不重复的最长字串的长度?
package main
import (
"fmt"
"strings"
)
/*
* 暴力穷举方:
找出全部的无重复子串, 统计出最长的
*/
func lengthOfLongestSubstring(s string) int {
count := 0
sonStringMap := make(map[string]int)
for j := 0; j < len(s); j++ {
tmpString := s[j:]
subString := ""
for k, v := range []byte(tmpString) {
if strings.Contains(subString, string(v)) {
sonStringMap[subString]++
if k == len(tmpString) {
sonStringMap[subString]++
}
subString = ""
} else {
subString += string(v)
if k == len(tmpString)-1 {
sonStringMap[subString]++
}
}
}
}
//fmt.Println(sonStringMap)
for k, _ := range sonStringMap {
if count < len(k) {
count = len(k)
}
}
return count
}
func lengthOfLongestSubstring1(s string) int {
m := make(map[byte]int)
res := 0
left := 0
for i := 0; i < len(s); i++ {
if m[s[i]] > 0 && left < m[s[i]] {
left = m[s[i]]
}
m[s[i]] = i + 1
if i-left+1 > res {
res = i - left + 1
}
}
return res
}
func lengthOfLongestSubstring2(s string) int {
m := make(map[byte]int)
res := 0
left := 0
for i := 0; i < len(s); i++ {
if m[[]byte(s)[i]] == 0 || m[[]byte(s)[i]] < left {
res = func(a, b int) int {
if a > b {
return a
}
return b
}(res, i-left+1)
} else {
left = m[s[i]]
}
m[s[i]] = i + 1
}
return res
}
//寻找最长不含有重复字符的子串,里面的rune直接把中文转为一个字节,中英文一起操作
func lengthOfLongestSubstring3(s string) int {
lastOcc := make(map[rune]int) // map用于存放char index
srart := 0
maxLength := 0
for i, ch := range []rune(s) {
if lastI, ok := lastOcc[ch]; ok && lastI >= srart {
srart = lastI + 1
}
if i-srart+1 > maxLength {
maxLength = i - srart + 1
}
lastOcc[ch] = i
}
return maxLength
}
func main() {
str := "abcdabsdkljlkdll122300GHJKLabcdUJMRFGHyhjmkecvxbwnjkmc;"
fmt.Println(lengthOfLongestSubstring(str))
fmt.Println(lengthOfLongestSubstring1(str))
fmt.Println(lengthOfLongestSubstring2(str))
fmt.Println(lengthOfLongestSubstring3(str))
}
执行:
root@ubuntu:~/zz# go run main.go
20
20
20
20
root@ubuntu:~/zz#