下文将介绍三种方法,求解问题类型:
1. 子串在主串中出现次数
2. 子串在主串中每次出现的下标位置
以此题为例:
题目链接:https://www.luogu.com.cn/problem/P8195
解法一:kmp
#include<iostream>
#include <string>
using namespace std;
const int N = 1e6 + 10;
int ne[N];
string p("chuanzhi"),t;
void getNext() {
int m = p.length();
int j = 0,k = -1;
ne[0] = -1;
while(j < m) {
if(k == -1 || p[j] == p[k]) {
ne[++j] = ++k;
} else {
k = ne[k];
}
}
}
int kmp() {
int i = 0,j = 0,r = 0;
int n = t.length(),m = p.length();
while(i < n) {
if(j == -1 || p[j] == t[i]) {
i++;
j++;
} else {
j = ne[j];
}
if(j == m) {
r++;
j = ne[j];
}
}
return r;
}
int main()
{
cin >> t;
getNext();
int res = kmp();
printf("%d",res);
return 0;
}
解法二:find
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
string s;
cin >> s;
string tt = "chuanzhi";
int res = 0, i = 0;
while(s.find(tt, i) != -1) {
res++;
i = s.find(tt, i) + 1;
}
cout << res;
return 0;
}
解法三:substr
#include <iostream>
#include <string>
using namespace std;
int main() {
string s, t("chuanzhi");
cin >> s;
int ls = s.size(), lt = t.size();
int cnt = 0;
for(int i = 0; i <= ls - lt; i++) {
if(s.substr(i, lt) == t)
cnt++;
}
cout << cnt;
return 0;
}
补充: count()
查找在字符串 / 数组
中,元素(字符/数值
)出现的次数
例如
#include <algorithm> //头文件
string s;
char c;
要查找在 s 中 c 的出现次数
则:
res = count(s.begin(), s.end(), c)
标签:string,int,res,++,ne,substr,-----,字符串,include
From: https://blog.csdn.net/m0_72256122/article/details/136784953