Accepted Two Line Java Solution


  • 0
    M

    My original solution is more "by the books", which includes comparing all possible substrings one by one:

    public int strStr(String haystack, String needle) {
    	if(haystack == null) return  -1;
            int l1 = haystack.length(), l2 = needle.length();
            if(l1 == 0 && l2 == 0) {
                return 0;
            }
            for(int i = 0; i <= l1 - l2; i++) {
                if(haystack.substring(i, i+ l2).equals(needle)){
                    return i;
                }
            }
            return -1;
    }
    

    After finishing that, I realizes there is an simpler way of doing this by using .indexOf(), which is basically java version of strStr() itself:

    public int strStr(String haystack, String needle) {
    	if(haystack == null) return -1;
    	return haystack.indexOf(needle);
    }
    

    This solution utilizes the existing String.indexOf() function, which returns the exact same result as required.


Log in to reply
 

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