求给定子串的next[]数组

    1. // nextArr 确定一个子串的next数组
    2. func nextArr(str string) []int {
    3. var slice = make([]int, 0)
    4. slice = append(slice, -1)
    5. for i := 2; i <= len(str); i++ {
    6. var j = 1
    7. for {
    8. prefix := str[:i-1-j]
    9. suffix := str[j : i-1]
    10. if prefix != "" && prefix == suffix {
    11. slice = append(slice, len(prefix))
    12. break
    13. }
    14. j++
    15. if j >= i {
    16. slice = append(slice, 0)
    17. break
    18. }
    19. }
    20. }
    21. return slice
    22. }

    根据next数组及查找目标字符串位置

    1. func FindStr(origin string, target string) int {
    2. if target == origin {
    3. return 0
    4. }
    5. if origin == "" {
    6. return -1
    7. }
    8. // next数组
    9. arr := nextArr(target)
    10. return findStr(origin, target, arr)
    11. }
    12. // findStr 私有查找字符串
    13. func findStr(str string, target string, arr []int) int {
    14. var i = 0
    15. var j = 0
    16. for {
    17. origin := str[i]
    18. t := target[j]
    19. if origin == t {
    20. i++
    21. j++
    22. } else {
    23. next := arr[j]
    24. if next < 0 {
    25. // 移动源字符串
    26. i++
    27. } else {
    28. // 移动模式串
    29. j = next
    30. }
    31. }
    32. if j == len(target) || i == len(str) {
    33. break
    34. }
    35. }
    36. if j == len(target) {
    37. return i - len(target)
    38. } else {
    39. return -1
    40. }
    41. }

    demo

    1. func main() {
    2. var str = "abcababcdsdohjd"
    3. var target = "ababcd"
    4. arr := nextArr(target)
    5. fmt.Println("next数组:", arr)
    6. //
    7. index := FindStr(str, target)
    8. if index < 0 {
    9. fmt.Println("未找到目标字符串!")
    10. } else {
    11. fmt.Println("找到目标字符串,起始位置index = ", index)
    12. }
    13. }