kmp算法

 


#include 
<string>
#include 
<vector>
using namespace std;

vector
<int> * kmp_next(string &substr)
{
 //next[i]存储的数字意义:
 //当text[tp]与substr[i+1]不匹配的时候,
 //应该让text[tp]来继续与substr[next[i]]来进行比较,
 //因为substr[0]...substr[next[i]-1]与text[next[i]-tp]...text[tp-1]相同,

    
static vector<int> next(substr.length());
    next[
0]=0;
    
int temp;
    
for (int i=1;i<substr.length();i++)
    
{
        temp 
=  next[i-1];//Get last value
        
while(substr[i]!=substr[temp] && temp>0)
            temp
=next[temp-1];
        
if (substr[i]==substr[temp])
            next[i]
=temp+1;//前面存在字符和当前比较的字符的前一个字符相同的,所以找那个字符的下
//一 个 字符来比较
        
else
            next[i]
=0;//前面没有字符和当前比较的字符的前一个字符相同的的,所以找来substr的首字符来重新比较
    }

    
return &next;
}


bool kmp_search(string& text,string &substr,int&pos)
{
    vector
<int> *next = kmp_next(substr);

    
int j=0;
    
int i=0;
    
for (i=0;i<text.length();i++)
    
{
        
while(text[i]!=substr[j]&&j>0)
            j
=(*next)[j-1];
        
if (text[i]==substr[j])
            j
++;
        
if (j==substr.length())
        
{
            pos 
= i-j+1;
            
return true;
        }

    }

    
if (i==text.length())
    
{
        
return false;
    }

}

int search(string&text, string &substr)
{
    
int subpos =0;
    
int count=0;
    
string tmptext = text;
    
while (kmp_search(tmptext,substr,subpos))
    
{
        count
++;
        tmptext 
= tmptext.substr(subpos+substr.length(),text.length()-(subpos+substr.length()));
    }

    
return count;
}
### KMP算法的实现与原理 KMP(Knuth-Morris-Pratt)算法是一种高效的字符串匹配算法,其核心思想是通过构建部分匹配表(也称为`next`数组或`failure`函数),避免在模式串匹配失败时对文本串进行回溯,从而降低时间复杂度[^1]。 #### 一、KMP算法的核心原理 KMP算法的关键在于利用模式串的部分匹配信息,构建一个最长公共前后缀表(通常称为`next`数组)。当匹配失败时,算法根据`next`数组中的值跳转到适当的位置继续匹配,而不是简单地将文本串指针回退。这种方法确保了文本串只需被扫描一次,时间复杂度为 \(O(n + m)\),其中 \(n\) 是文本串长度,\(m\) 是模式串长度[^3]。 #### 二、部分匹配表(`next`数组)的构造 `next`数组记录了模式串中每个位置对应的最长公共前后缀长度。例如,对于模式串 `"ABABC"`,其`next`数组为 `[0, 0, 1, 2, 0]`。以下是构造`next`数组的步骤: ```python def compute_next(pattern): n = len(pattern) next_array = [0] * n j = 0 # 前缀末尾索引 for i in range(1, n): # 后缀末尾索引从1开始 while j > 0 and pattern[i] != pattern[j]: j = next_array[j - 1] if pattern[i] == pattern[j]: j += 1 next_array[i] = j return next_array ``` #### 三、KMP算法的实现 基于上述`next`数组,可以实现高效的字符串匹配。以下是完整的KMP算法实现代码: ```python def kmp_search(text, pattern): next_array = compute_next(pattern) # 构造next数组 n, m = len(text), len(pattern) j = 0 # 模式串指针 for i in range(n): # 遍历文本串 while j > 0 and text[i] != pattern[j]: j = next_array[j - 1] if text[i] == pattern[j]: j += 1 if j == m: # 匹配成功 return i - m + 1 # 返回匹配起始位置 return -1 # 匹配失败 ``` #### 四、示例分析 假设文本串为 `"ABABABCABABC"`, 模式串为 `"ABABC"`,则通过KMP算法可以快速找到模式串在文本串中的首次出现位置。具体过程如下: 1. 初始化文本串指针 `i = 0` 和模式串指针 `j = 0`。 2. 依次比较字符,若匹配失败,则根据`next`数组调整模式串指针 `j`。 3. 当模式串完全匹配时,返回匹配起始位置。 #### 五、C语言实现示例 除了Python,KMP算法也可以用C语言实现。以下是一个简单的C语言版本: ```c #include <stdio.h> #include <string.h> void computeNext(const char* pattern, int* next, int m) { int j = 0; next[0] = 0; for (int i = 1; i < m; i++) { while (j > 0 && pattern[i] != pattern[j]) { j = next[j - 1]; } if (pattern[i] == pattern[j]) { j++; } next[i] = j; } } int kmpSearch(const char* text, const char* pattern) { int n = strlen(text); int m = strlen(pattern); int next[m]; computeNext(pattern, next, m); int j = 0; for (int i = 0; i < n; i++) { while (j > 0 && text[i] != pattern[j]) { j = next[j - 1]; } if (text[i] == pattern[j]) { j++; } if (j == m) { return i - m + 1; } } return -1; } int main() { const char* text = "ABABABCABABC"; const char* pattern = "ABABC"; int result = kmpSearch(text, pattern); printf("Pattern found at index: %d\n", result); return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值