28.实现strStr() (KMP算法)

28.实现strStr() (KMP算法)_第1张图片

Python3代码:

class Solution:
    #获取next数组
    def get_next(self, needle: str) -> List[int]:
        i = 0
        j = -1
        next_val = [-1] * len(needle)
        while i < len(needle) -1:
            if j==-1 or needle[i] == needle[j]:
                i += 1
                j += 1
                if i < len(needle) and needle[i] != needle[j]:
                    next_val[i] = j
                else:
                    next_val[i] = next_val[j]
            else:
                j = next_val[j]
        return next_val

    def strStr(self, haystack: str, needle: str) -> int:
        i = 0
        j = 0
        next_val = self.get_next(needle)
        while i

C++代码(代码参考他人,思路都是KMP):

class Solution {
public:
    int strStr(string haystack, string needle) {
        if(needle.size()==0) return 0;
        int nsize=needle.size();
        int hsize=haystack.size();
        int pos=-1;
        int nextVal[nsize];
        getNextVal(nextVal,needle);
        int i=0,j=0;
        while(i=nsize){
                pos=i-nsize;//因爲匹配完成了,所以i在單詞最後
                break;
            }
           i++;
        }
        return pos;
    }

    void getNextVal(int* nextVal,string& s){
        int j=0,i=1;
        nextVal[0]=0;
        int size=s.size();
        while(i

 

你可能感兴趣的:(LeetCode刷题)