Easy 5ms Java Solution using charAt pruely


  • 1
    public int strStr(String haystack, String needle) {
        if(needle.isEmpty())
            return 0;
        for(int i=0; i<haystack.length(); i++) {
            if(haystack.length()-i < needle.length())
                return -1;
            if(haystack.charAt(i) == needle.charAt(0)) {
                boolean match = true;
                for(int j=1; j<needle.length(); j++) {
                    if(needle.charAt(j) != haystack.charAt(i+j)) {
                        match = false;
                        break;
                    }
                }
                if(match)
                    return i;
            }
        }
        return -1;
    }

Log in to reply
 

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