codevs 1204 寻找子串位置

题目描述 Description

给出字符串a和字符串b,保证b是a的一个子串,请你输出b在a中第一次出现的位置。

输入描述 Input Description

仅一行包含两个字符串a和b

输出描述 Output Description

仅一行一个整数

样例输入 Sample Input

abcd bc

样例输出 Sample Output

2

数据范围及提示 Data Size & Hint

字符串的长度均不超过100

Pascal用户请注意:两个字符串之间可能包含多个空格

//详细的KMP讲解,我觉得比较好的http://kb.cnblogs.com/page/176818/

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int main()
{
	char a[101],b[101];
	int l1,l2,f[101];
	cin>>a;
	cin>>b;
	l1=strlen(a);
	l2=strlen(b);
	f[0]=0;
	//对b串进行自匹配,保存在f数组中 ↓ 
	for (int i=1,j=0;i<l2;i++)
	  {
	  	 while (j>0&&b[i]!=b[j]) j=f[j];
	     if (b[i]==b[j]) j++;
	       f[i]=j;
	  }
	//对b串进行自匹配,保存在f数组中 ↑
	  
	for (int i=0,j=0;i<l1;i++)//对a,b串进行匹配 
	  {
	  	 while (j>0&&a[i]!=b[j]) j=f[j];//若是a,b串不匹配,则将b串正在匹配的位置移动到它上一个重复的位置  
	  	 if (a[i]==b[j]) j++;
	  	 if (j==l2)
	  	   {
	  	      cout<<i-l2+2;
			  break;	
		   }
	  }
	  
	return 0;
}

  

I'm so lost but not afraid ,I've been broken and raise again
原文地址:https://www.cnblogs.com/sjymj/p/5239810.html