LeetCode 28. Implement strStr()

虽然分在EASY里面....模式匹配模板题。用KMP就行。

void buildNext(string p,int next[]){
  
    int pLen = p.length();  
    next[0] = -1;  
    int t = -1;  
    int j = 0;  
    while (j < pLen - 1){ 
        if (t == -1 || p[j] == p[t]){  
            ++j;  
            ++t;  
            next[j] = t;  
        }else{  
            t = next[t];  
        }  
    }
} 

class Solution { 
public:
    int strStr(string s, string p) {
        int i = 0,j = 0;  
        int sLen = s.length();  
        int pLen = p.length();
        if (!pLen) return 0;
        int next[pLen];
        buildNext(p,next);
        while (i < sLen && j < pLen){     
            if (j == -1 || s[i] == p[j]){  
                i++;  
                j++;  
            }else{  
                j = next[j];  
            }  
        }  
        if (j == pLen)  
            return i - j;  
        else  
            return -1;  
    }
};

 刚刚看了一眼和暴力速度居然一样。。。

class Solution {
public:
    int strStr(string haystack, string needle) {
        if(needle.empty())
            return 0;
        int index1=0;
        int index2=0;
        while(index1<haystack.length() && index2<needle.length()) {
            if(haystack[index1] == needle[index2]){
                index2++;
            }
            else {
                index1 -=index2;
                index2 = 0;
            }
            
            index1++;
        }
        if(index2 == needle.length())
            return index1-index2;
        else
            return -1;
    }
};

 

posted @ 2018-09-14 11:37  Travelller  阅读(96)  评论(0编辑  收藏  举报