leetcode:28. Implement strStr()

28. Implement strStr()

Description

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1
Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().

Answer

package main

import "fmt"

func strStr(haystack string, needle string) int {

    for i := 0; ; i++ { //控制原字符串
        for j := 0; ; j++ { //j控制待比较字符串
            //全部比较完成时,返回下标位置
            if j == len(needle) {
                return i
            }
            //判断是否溢出
            if i+j == len(haystack) {
                return -1
            }
            //如果不相等,就退出当前循环
            if haystack[i+j] != needle[j] {
                break
            }
        }
    }

}

func main() {
    fmt.Println(strStr("hello", "llo"))
}



你可能感兴趣的:(leetcode:28. Implement strStr())