LeetCode -- 28. Implement strStr()

My solution:

class Solution {
public:
    int strStr(string haystack, string needle) {
        int hsize = haystack.size();
        int nsize = needle.size();
        if(hsize<nsize) return -1;
        if(needle == "" ||haystack == "") return 0;
        
        for(int i=0; i<hsize; i++){
            if(haystack[i] == needle[0]){
                for(int j=1; j<nsize; j++){
                    if(haystack[i+j] != needle[j])
                        break;
         
                    if(j == nsize-1) return i;
                }
                if(nsize == 1) return i;
            }
        }
        return -1;
    }
};

 

Other guy's solution

    int strStr(string haystack, string needle) {

        if(haystack.size() < needle.size())
            return -1;
        
        int index = 0;
        int i,j;
        for(i = 0, j = 0;i < haystack.size() && j < needle.size();){
            if(haystack[i] == needle[j]){
                i++; j++;
            }else{
               index++;
               i = index;
               j = 0;
            }
        }
    
        if(j == needle.size())
            return index;
        return -1;
   }

  

猜你喜欢

转载自www.cnblogs.com/feliz/p/10916521.html