字符串匹配的算法总结

一、KMP模板 

实现:

主要需要完成next数组决字符串的匹配。

返回的是needle字符串首次匹配 haystack字符串的首字符的下标(下标是针对haystack字符串的)。

模板:

 1 int strStr(string haystack, string needle) {
 2         int n = haystack.size(), m = needle.size();
 3         if(m == 0) return 0;
 4         vector<int> next(m);
 5         for(int i=1,j=0;i<m;i++){//完成next数组
 6             while(j>0 && needle[i]!=needle[j]){
 7                 j = next[j-1];
 8             }
 9             if(needle[i] == needle[j]){
10                 j++;
11             }
12             next[i] = j;
13         }
14         for(int i=0,j=0;i<n;i++){//完成字符串的匹配
15             while(j>0 && haystack[i] != needle[j]){
16                 j = next[j-1];
17             }
18             if(haystack[i] == needle[j]) j++;
19             if(j == m) return i-m+1;
20         }
21         return -1;
22     }

 

 

参考链接:https://leetcode-cn.com/problems/implement-strstr/solution/shi-xian-strstr-by-leetcode-solution-ds6y/

 

二、Rabin-Karp 算法

思想:

不直接逐位对比模式串pat和text是否相等,而是利用哈希算法,计算模式串和子串的哈希值,如果哈希值不相等,那么很明显字符串也不相等,如果相等,由于哈希算法可能会存在哈希冲突的可能,因此再用朴素算法判断其是否真正相等。

参考链接:https://coolcao.com/2020/08/20/rabin-karp/

 

三、string的find函数

string中find()返回值是字母在母串中的位置(下标记录),如果没有找到,那么会返回一个特别的标记npos。(返回值可以看成是一个int型的数)

参考例题:leedcode686

代码:

 1 class Solution {
 2 public: 
 3     
 4     int repeatedStringMatch(string a, string b) {
 5         string s = a;
 6         while(s.size() <= b.size()){
 7             s += a;
 8         }
 9         s += a;
10         size_t index = s.find(b);
11         if(index == string::npos) return -1;
12         return (b.size() + index -1)/a.size() + 1;
13     }
14 };

 

posted @ 2021-12-24 20:49  白雪儿  Views(25)  Comments(0Edit  收藏  举报