博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
字符串匹配算法BF和KMP总结
阅读量:4364 次
发布时间:2019-06-07

本文共 2206 字,大约阅读时间需要 7 分钟。

背景

来看一道leetcode题目:

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

让我们找到第一个子串的位置,这就是典型的字符串匹配问题。首先想到的就是暴力求解,时间复杂度O(mn).

BF算法实现

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

但是我们可以发现,其实有些字符串我们已经匹配过了,就不需要再次匹配了,这就是经典的KMP算法,时间复杂度为O(m + n)。KMP算法的讲的比较好的,可以参考这个博客:

KMP算法实现

class Solution {public:    int strStr(string haystack, string needle) {        if (haystack.size() == 0) {            if (needle.size() == 0)                return 0;            else                return -1;        } else if (needle.size() == 0)            return 0;        if (haystack.size() < needle.size())            return -1;        vector
Next(needle.size()); getNext(needle, Next); for (int i = 0; i < haystack.size(); ) { // 如果剩下的字符串比目标字符串更短,那么直接返回-1. if (haystack.size() - i < needle.size()) return -1; int num = 0; int step = 1; for (int j = 0; j < needle.size(); j++) { if (haystack[i + j] == needle[j]) { num++; } else break; } if (num == needle.size()) return i; if (num) step = num - Next[num - 1]; i = i + step; } return -1; } void getNext(string needle, vector
& next) { int k = 0; next[0] = 0; for (int i = 1; i < needle.size(); i++) { while (k > 0 && needle[i] != needle[k]) k = next[k - 1]; if (needle[i] == needle[k]) k++; next[i] = k; } }};

转载于:https://www.cnblogs.com/zhonghuasong/p/7088703.html

你可能感兴趣的文章
札记-20190531
查看>>
简练软考知识点整理-项目监控过程组
查看>>
排序算法 - 函数 Char* Revert(Char* pStr),将字符串pStr逆序
查看>>
Vue.js Client-Side Storage;( Web Storage/localStorage)
查看>>
JavaWeb学习总结(四十九)——简单模拟Sping MVC
查看>>
XOR (莫队)
查看>>
开发环境,生产环境,测试环境的区别
查看>>
|洛谷|排序|P1309 瑞士轮
查看>>
Java简介
查看>>
简单排序实现
查看>>
.Net程序员学用Oracle系列(7):视图、函数、存储过程、包
查看>>
setStreamMute无法Mute部分stream
查看>>
Android 绑定类型服务---绑定服务
查看>>
bzoj 4555 求和
查看>>
Spring的工作原理
查看>>
四分树 (Quadtrees UVA - 297)
查看>>
Quartz 学习
查看>>
获取项目路径
查看>>
[第1组]头脑风暴+核心竞争力+功能集+NABCD
查看>>
E20180518-hm
查看>>