1.自拟

    1. //寻找最长不含有重复字符的子串
    2. package main
    3. import "fmt"
    4. func main() {
    5. var str = "abcdabcc"
    6. var ch = make(map[byte]int)
    7. var long int
    8. var moreLong int
    9. var longStr []byte
    10. var moreLongStr []byte
    11. moreLongStr = nil
    12. for i := 0; i < len(str); i++ {
    13. longStr = nil
    14. for j := i; j < len(str); j++ {
    15. if ch[str[j]] == 0 {
    16. ch[str[j]] = 1
    17. long++
    18. longStr = append(longStr, str[j])
    19. }else {
    20. if long > moreLong {
    21. moreLong = long
    22. moreLongStr = longStr
    23. }
    24. break
    25. }
    26. }
    27. }
    28. fmt.Println(string(moreLongStr))
    29. }

    2.优化版

    1. package main
    2. import "fmt"
    3. func noRepeatStr(str string) (maxLength int,subStr string){
    4. start := 0
    5. lastOccurred := make(map[byte]int)
    6. for i, v := range []byte(str) {
    7. if lastI, ok := lastOccurred[v]; ok && lastI >= start {
    8. start = lastI + 1
    9. }
    10. if i-start+1 > maxLength{
    11. maxLength = i - start + 1
    12. subStr = str[start:i+1]
    13. }
    14. lastOccurred[v] = i
    15. }
    16. return
    17. }
    18. func main() {
    19. len, subStr := noRepeatStr("abcdacba")
    20. fmt.Printf("length:%d,str:%s", len, subStr)
    21. }

    3.国际版

    1. package main
    2. import "fmt"
    3. func noRepeatStr(str string) (maxLength int,subStr string){
    4. start := 0
    5. lastOccurred := make(map[rune]int)
    6. for i, v := range []rune(str) {
    7. if lastI, ok := lastOccurred[v]; ok && lastI >= start {
    8. start = lastI + 1
    9. }
    10. if i-start+1 > maxLength{
    11. maxLength = i - start + 1
    12. subStr = string([]rune(str)[start:i+1])
    13. }
    14. lastOccurred[v] = i
    15. }
    16. return
    17. }
    18. func main() {
    19. len, subStr := noRepeatStr("abcdacba")
    20. fmt.Printf("length:%d,str:%s\n", len, subStr)
    21. len, subStr = noRepeatStr("你好世界你好")
    22. fmt.Printf("length:%d,str:%s", len, subStr)
    23. }