28. Implement strStr()

Descritpion

Implement strStr().

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

Note: haystack的意思是干草堆。题意为大海捞针 LOL~

Solution

Basic

Brute-force

public class Solution {
    public int strStr(String haystack, String needle) {
        if (haystack == null || needle == null) {
            return -1;
        }
        
        int hl = haystack.length();
        int nl = needle.length();
        int j = 0;
        
        for (int i = 0; i <= hl - nl; ++i) {
            for (j = 0; j < nl && haystack.charAt(i + j) == needle.charAt(j); ++j) { }
            if (j == nl) return i;
        }
        
        return -1;
    }
}

TODO: Optimisation

KMP

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