Thursday, February 1, 2018

[2018-Interview] Implement strStr()

Original question: https://leetcode.com/problems/implement-strstr/description/

My Answer:



class Solution {
    public int strStr(String haystack, String needle) {
        if (haystack != null && needle != null && (haystack.equals(needle) || needle.length() == 0)) {
            return 0;
        }
        if (haystack == null || needle == null || needle.length() > haystack.length() ) {
            return -1;
        }
        // brute force
        int h = 0;
        for (; h < haystack.length() - needle.length() + 1; h ++) {
            int i = 0;
            for (; i < needle.length(); i++) {
                if (haystack.charAt(h + i) != needle.charAt(i)) {
                    break;
                }
            }
            if (i == needle.length()) {
                return h;
            }
        }
        return -1;
    }
}

KMP algorithm should be the best solution, but it is difficult to understand and implement during interview.

KMP Article: http://www.matrix67.com/blog/archives/115

No comments:

Post a Comment