Implement strStr()

Implement strStr().

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

Time Complexity
O(N^2)
Space Complexity
O(1)

思路

When haystack and needle both has 0 length, it is valid, so we need to check from length 0. We only need to check the haystack length - the needle length, because if it is bigger than this length, it won't success.

代码

public int strStr(String haystack, String needle) {
    //corner case
    if(haystack == null || needle == null) return -1;
    int hlen = haystack.length(), nlen = needle.length();
    int start = 0;
    while(start <= hlen - nlen){
        int i1 = start, i2 = 0;
        while(i2 < nlen && haystack.charAt(i1) == needle.charAt(i2)){
            i1++;
            i2++;
        }
        if(i2 == nlen) return start;
        start++;
    }
    return -1;
}

Test Cases

""
"a"
expected answer -1
""""
expected answer 0


annielulu
5 声望5 粉丝