LeetCode 28.

Tags:

Complexity

  • Time complexity: O(n)

  • Space complexity: O(1)

Code

class Solution {
    public int strStr(String haystack, String needle) {
        int left2Right = 10001, right2Left = 10001;
        int hlen = haystack.length(), nlen = needle.length();
        boolean match = false;
        for (int i=0; i<hlen; i++) {
            if (haystack.charAt(i) == needle.charAt(0)) {
                match = true;
                for (int j=1; j<nlen; j++) {
                    if (i+j >= hlen || haystack.charAt(i+j) != needle.charAt(j)) {
                        match = false;
                        i+=(j-1);
                        break;
                    }
                }
                if (match) {
                    left2Right = i;
                    break;
                }
            }
        }

        for (int i=hlen-1; i>=0; i--) {
            if (haystack.charAt(i) == needle.charAt(nlen-1)) {
                match = true;
                for (int j=1; j<nlen; j++) {
                    if (i-j < 0 || haystack.charAt(i-j) != needle.charAt(nlen-1-j)) {
                        match = false;
                        i-=(j-1);
                        break;
                    }
                }
                if (match) {
                    i-=(nlen-1);
                    right2Left = i;
                }
            }
        }
        return Math.min(left2Right, right2Left) == 10001 ? -1 : Math.min(left2Right, right2Left);
    }
}

Check out the description of this problem at LC 28.