Early return 3 ms java solution(beats 70%)


  • 0
    F
    public int strStr(String haystack, String needle) {
            if(needle.length()==0)return 0;
            if(needle.length()>haystack.length())return -1;
            char[] hay=haystack.toCharArray();
            boolean found;
            for(int i=0;i<haystack.length();i++)
            {
                int j=i;
                found=true;
                if(hay[i]==needle.charAt(0)){
                    for(char c:needle.toCharArray()){
                        if(j>=haystack.length()||c!=hay[j++]){
                            found=false;
                            break;
                        }
                    }
                    if(found)
                        return i;
                    if(j==hay.length)return -1;
                }
            }
            return -1;     
        }
    

Log in to reply
 

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