A c++ brute-force solution. 4MS


  • 0
    int strStr(string haystack, string needle) {
            int nsize = needle.size(), hsize = haystack.size();
            if(nsize==0) return 0;
            if(hsize==0||nsize>hsize) return -1;
            
            //using brute-force;
            for(int i=0; i<hsize; i++){
                bool finish=true;
                for(int j=0; j<=nsize-1; j++){
                    if(i+j>hsize-1) return -1;
                    if(haystack[i+j]!=needle[j]) { finish=false;break;}
                }
                if(finish) return i;
            }
            return -1;
        }

Log in to reply
 

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