Java easy to understand solutions.


  • 12
    C
    public int strStr1(String haystack, String needle) {
        return haystack.indexOf(needle);
    }
    
    public int strStr(String haystack, String needle) {
        if (haystack == null || needle == null)
            return -1;
        int l1 = haystack.length();
        int l2 = needle.length();
        for (int i = 0; i < l1-l2+1; i++) {
            int count = 0;
            while (count < l2 && haystack.charAt(i+count) == needle.charAt(count))
                count++;
            if (count == l2)
                return i;
        }
        return -1;
    }

  • 0
    I

    in your second solution, line eight (count<l2) is not necessary since there's a IF condition(count==l2) to guarantee that needle is the first time showing up, but in the While Loop (still in line 8) you have to add one more condition(l1-i>=l2) make sure that string index(i+count) will not be out of range.


  • 1
    N

    @irinalu
    What you replied is partially true, but the thing is that in the test case, there is haystack "" and needle "". If there is no count < l2, then after the first check, count increases to 1, and haystack.charAt(i + count) is out of boundary, and it fails in the test case.
    Either one has to put the length check at the very first beginning, or add the boundary check in the while clause.


Log in to reply
 

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