28. Implement strStr()

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

Solution1:Two Pointers 对比

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

other Solution:Rabin karp / KMP

Solution Code:

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

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