【笔试练习题】字符串匹配算法KMP

一句话总结:空间换时间,用一个next数组保存不匹配时下一次开始比较时两个字符串指针的位置;next[ i ]中保存的是前i个字符后缀与前缀相同的个数。

参考资料:

【1】一个将KMP的视频,很好理解,而且很短,只有十来分钟。

https://www.bilibili.com/video/av3246487?from=search&seid=18035591679131870458

【2】博客

https://www.cnblogs.com/zzzdp/p/9416570.html

https://www.nowcoder.com/discuss/4236?type=0&order=0&pos=309&page=0?from=wb

练习题:leetcode 28 Implement strStr()

class Solution {
public:
    /* 暴力运算 4ms 9MB*/
    /*
    int strStr(string haystack, string needle) {
        int m = haystack.size();
        int n = needle.size();
        for(int i = 0; i <= m-n; i ++)
        {
            int j;
            for(j = 0; j < n; j ++)
            {
                if(haystack[i+j] != needle[j])
                    break;
            }
            if(j == n)
                return i;
        }
        return -1;
    }
    */
    /* KMP */
    void get_next(string str, vector<int> &next){
        int i = 0; 
        int j = 1;
        while(j < str.size()){
            while(i > 0 && str[i] != str[j])
            {
                i = next[i - 1];
            }
            if(str[i] == str[j]){
                next[j] = i + 1;
                j++;
                i++;
            }
            else {
                j++;
            }
        }
    }
    
    int get_str(string text, string pattern) {
        int m = text.size();
        int n = pattern.size();
        vector<int> next(n, 0);
        get_next(pattern, next);
        int i = 0; 
        int j = 0;
        while(i < m){
            while(j > 0 && text[i] != pattern[j]){ // 找到pattern开始比较的字符
                j = next[j - 1];
            }
            if(text[i] == pattern[j]){
                j++;
                i++;
                if(j == n){
                    return i - n;
                }
            }
            else{ // 此时pattern的j == 0,并且text[i] != pattern[j],因此i自增
                i++;
            }
        }
        return -1;
    }
    int strStr(string haystack, string needle) {
        if(needle.size() == 0){
            return 0;
        }
        return get_str(haystack, needle);
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值