My easy understand C++ solution


  • -1
    K
    int strStr(string haystack, string needle) {
    if(haystack=="" && needle=="") return 0;
    if(haystack!="" && needle=="") return 0;
    if(haystack.size()<needle.size()) return -1;
    
    vector<char> hay(haystack.begin(),haystack.end());
    vector<char> need(needle.begin(),needle.end());
    int temp=0,j=0;
    
    for(int i=0;i<hay.size();i++){
        if(hay[i]!=need[0]){
            continue;
        }else{
            temp=i;
            if(needle.size()>haystack.size()-temp) return -1;
            for( j=0;j<need.size();j++){
                if(hay[i]==need[j]){
                    i++;
                    continue;
                }
                else {
                    i=temp;
                    break;
                }
            }
            if(j==need.size()) return temp;
        }
    }
    return -1;
    
    }

Log in to reply
 

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