1.自拟
//寻找最长不含有重复字符的子串
package main
import "fmt"
func main() {
var str = "abcdabcc"
var ch = make(map[byte]int)
var long int
var moreLong int
var longStr []byte
var moreLongStr []byte
moreLongStr = nil
for i := 0; i < len(str); i++ {
longStr = nil
for j := i; j < len(str); j++ {
if ch[str[j]] == 0 {
ch[str[j]] = 1
long++
longStr = append(longStr, str[j])
}else {
if long > moreLong {
moreLong = long
moreLongStr = longStr
}
break
}
}
}
fmt.Println(string(moreLongStr))
}
2.优化版
package main
import "fmt"
func noRepeatStr(str string) (maxLength int,subStr string){
start := 0
lastOccurred := make(map[byte]int)
for i, v := range []byte(str) {
if lastI, ok := lastOccurred[v]; ok && lastI >= start {
start = lastI + 1
}
if i-start+1 > maxLength{
maxLength = i - start + 1
subStr = str[start:i+1]
}
lastOccurred[v] = i
}
return
}
func main() {
len, subStr := noRepeatStr("abcdacba")
fmt.Printf("length:%d,str:%s", len, subStr)
}
3.国际版
package main
import "fmt"
func noRepeatStr(str string) (maxLength int,subStr string){
start := 0
lastOccurred := make(map[rune]int)
for i, v := range []rune(str) {
if lastI, ok := lastOccurred[v]; ok && lastI >= start {
start = lastI + 1
}
if i-start+1 > maxLength{
maxLength = i - start + 1
subStr = string([]rune(str)[start:i+1])
}
lastOccurred[v] = i
}
return
}
func main() {
len, subStr := noRepeatStr("abcdacba")
fmt.Printf("length:%d,str:%s\n", len, subStr)
len, subStr = noRepeatStr("你好世界你好")
fmt.Printf("length:%d,str:%s", len, subStr)
}