class Solution {
    public int strStr(String haystack, String needle) {
        if (haystack.length() < needle.length()) {
            return -1;
        }
        
        if (needle.length() == 0) {
            return 0;
        }

        char[] toMatch = haystack.toCharArray();
        char[] pattern = needle.toCharArray();
        for (int i = 0; i < toMatch.length - pattern.length + 1; i++) {
            if (toMatch[i] == pattern[0] && isMatch(toMatch, i, pattern, 0)) {
                return i;
            } 
        }
        return -1;
    }
    
    
    private boolean isMatch(char[] a, int i1, char[] b, int i2) {
        while (i1 < a.length && i2 < b.length && a[i1] == b[i2]) {
            i1++;
            i2++;
        }
        return i2 == b.length;
    }
}

 

We can avoid more duplicate work by check [0, haystack - needle + 1] length.

Need to revisit KMP

 

posted on 2017-08-30 14:14  keepshuatishuati  阅读(74)  评论(0编辑  收藏  举报