I challenge your elegance : )

  • 0

    Re: Elegant Java solution

    public int strStr(String haystack, String needle) {
        for(int i=0; i<(haystack.length()-needle.length()+1); i++) {
            int j = 0;
            for(; j<needle.length() && haystack.charAt(i+j)==needle.charAt(j); j++) {}
            if(j==needle.length()) return i;
        return -1;

    The "i<(haystack.length()-needle.length()+1)" added to inner for-loop termination condition handles cases such as:

    • haystack="" vs needle=""
    • haystack="a" vs needle="a"
    • haystack="aa" vs needle="aaaa"

    In the end we all used the brute force O(mn) solution... we are all SAVAGES....

Log in to reply

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