字符串匹配/查找字符串中子串存在次数/出现位置下标 问题----- {1.[find] 2.[substr] 3.[kmp]}

下文将介绍三种方法,求解问题类型:

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)

  • 14
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值