Title Description
Description
Given the string A and string B, to ensure that B is a substring of a, please output B in a where the first occurrence.
Enter a description
Input Description
Only one row contains two strings A and b
Output description
Output Description
One-line integer only
Sample input
Sample Input
ABCD BC
Sample output
Sample Output
2
Data range and Tips
Data Size & Hint
The length of the string does not exceed 100
Pascal user note: Two strings may contain multiple spaces
Detailed KMP explanation, I think the better 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;//self-matching the B-string, saved in the F-array ↓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; } Self-matching B-string, saved in F-array ↑ for (int i=0,j=0;i<l1;i++)//Match {while (J>0&&a[i]!=b[j]) to A/b string j=f[ j];//If A/b string does not match, move the position of the string that is being matched to its last duplicate position if (A[i]==b[j]) j + +; if (J==L2) { cout<<i-l2+2; break; } } return 0;}
Codevs 1204 Finding sub-string locations