Implement StrStr

Implement strStr().

strstr - locate a substring ( needle ) in a string ( haystack ).

Try not to use standard library string functions for this question.

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

NOTE:

Good clarification questions:

  1. What should be the return value if the needle is empty?

  2. What if both haystack and needle are empty?

For the purpose of this problem, assume that the return value should be -1 in both cases.

class Solution {
    public int strStr(final String haystack, final String needle) {
        if (needle.length() == 0)
            return -1;
        for (int i = 0; i <= haystack.length() - needle.length(); i++)
            if (haystack.substring(i, i + needle.length()).compareTo(needle) == 0)
                return i;

        return -1;
    }
}

Last updated