This test case doesn't make sense.

  • 21

    Input: "", ""
    Output: -1
    Expected: 0

    Basically there is nothing in the string, how do you get the index.

    If this test case is valid, then needle ="", haystack="anything" could return any value. since empty is everywhere.

  • 2

    Just because "" is everywhere, needle = "", haystack = "anything"" will return 0 for this question since it's the first index, I beg.

  • 0

    I agree. You can't find nothing in nothing. It's just logically undoable.

  • 0

    And so is the test case "a",""
    The empty string can be in the beginning or in the end.

  • 2

    I agree this does not make sense.
    But string::find in c++ has the same behavior.
    So there must be some reason backing the behavior.
    I do not consider the test case when writing the following code but it generates the correct result unexpectedly.
    That might be the reason...

        int strStr(string haystack, string needle) {
            int ns = needle.size();
            for(int h=0;h<(int)haystack.size()-ns+1;h++) {
                int n = 0;
                while(n < ns) 
                    if(haystack[h+n]==needle[n]) n++;
                    else break;
                if(n==ns) return h;
            return -1;

  • 3

    The first appearance of "" is at position 0...
    So somehow it does make sense...

  • -1
    This post is deleted!

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.