这道题挺简单的,但是没有考虑到 “a” 和 “a” 比较的情况,疏忽了 。

    1. func strStr(haystack string, needle string) int {
    2. if len(needle) == 0 {
    3. return 0
    4. }
    5. haystackBytes := []byte(haystack)
    6. needleBytes := []byte(needle)
    7. for i := 0; i <= len(haystackBytes) - len(needleBytes); i++ {
    8. match := true
    9. for j, nc := range needleBytes {
    10. if nc != haystack[i + j] {
    11. match = false
    12. break
    13. }
    14. }
    15. if match {
    16. return i
    17. }
    18. }
    19. return -1
    20. }
    21. func main() {
    22. fmt.Println(strStr("hello", "ll"))
    23. fmt.Println(strStr("aaaaa", "bba"))
    24. fmt.Println(strStr("hello", ""))
    25. fmt.Println(strStr("bba", "aaaaa"))
    26. fmt.Println(strStr("a", "a"))
    27. }