复旦13考研机试真题(1)--字符串匹配

对于主串M和模式串P,找到P在M中出现的所有子串的第一个字符在P中的位置。P中第一个字符所在的位置为0。首行的数字表示有多少组字符串。字符长度在106以内。
[输入及示例]

2
ababababa
ababa
aaa
aa

[输出及示例]

0 2 4
0 1

(相邻位置之间用一个空格隔开)
分析:这个题目我在牛客网上见到过,有人用stl中string的find函数也可以AC; 但是我查了一下find的时间复杂度应该是O(m*n), 按理来说极端测试用例应该过不了才对;这个题目我就两个解法都写一下吧,还有一种用KMP算法,时间复杂度O(m+n);

解法一:

#include<iostream>     
#include<string>
#include<vector>
using namespace std; 
 int main() { 
	 int n; 
	 scanf("%d", &n);
	 for (int i = 0; i < n; i++) {
		 string a, b;
		 int index;
		 vector<int>V;
		 cin >> a >> b;
		 index = a.find(b);
		 while (index != -1) {
			 V.push_back(index);
			 index = a.find(b, index + 1);
		 }
		 for (int i = 0; i < V.size(); i++) {
			 if (i != 0)
				 printf(" ");
			 printf("%d", V[i]);
		 }
		 printf("\n");
	 }
	 return 0;
}

解法二:

#include<iostream>     
#include<string>
#include<algorithm>
#include<vector>
using namespace std;  
int nnext[1000010];
void buildnext(const string& a) {
	fill(nnext, nnext + 1000010, 0);
	nnext[0] = -1;
	int L = a.length();
	int i = 0, j = -1;
	while (i < L) {
		if (j == -1 || a[i] == a[j]) {
			i++;
			j++;
			nnext[i] = j;
		}
		else
			j = nnext[j];
	}
} 
 int main() { 
	 int n; 
	 scanf("%d", &n);
	 for (int i = 0; i < n; i++) {
		 string a, b; 
		 vector<int>V;
		 cin >> a >> b;
		 buildnext(b);
		 int La = a.length();
		 int Lb = b.length();
		 int k = -1;
		 for (int j = -1; j < La;) {
			 if (k == -1 || a[j] == b[k]) {
				 j++;
				 k++;
			 }
			 else
				 k = nnext[k];
			 if (k == Lb) {
				 V.push_back(j - Lb);
				 k = nnext[k];
			 }  
		 }
		 for (int i = 0; i < V.size(); i++) {
			 if (i != 0)
				 printf(" ");
			 printf("%d", V[i]);
		 }
		 printf("\n");
	 }
	 return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值