LeetCode 28: Implement Strstr

Posted keepshuatishuati

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 28: Implement Strstr相关的知识,希望对你有一定的参考价值。

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

 

以上是关于LeetCode 28: Implement Strstr的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode---28. Implement strStr()

44. leetcode 28. Implement strStr()

leetcode 28. Implement strStr()

LeetCode OJ 28Implement strStr()

LeetCode_28. Implement strStr()

19.1.30 [LeetCode 28] Implement strStr()