codeves 1204

题意:2个字符串s,t.问t出现在s的首个位置。

思路:KMP模板,当然这里暴力也可以

 1 #include <iostream>
 2 #include <cstring>
 3 using namespace std;
 4 
 5 const int N = 1000002;
 6 int next[N];
 7 char S[N], T[N];
 8 int slen, tlen;
 9 
10 void getNext()
11 {
12     int j, k;
13     j = 0; k = -1; next[0] = -1;
14     while(j < tlen)
15         if(k == -1 || T[j] == T[k])
16             next[++j] = ++k;
17         else
18             k = next[k];
19 
20 }
21 int KMP_Index()
22 {
23     int i = 0, j = 0;
24     getNext();
25     while(i < slen && j < tlen)
26     {
27         if(j == -1 || S[i] == T[j])
28         {
29             i++; j++;
30         }
31         else
32             j = next[j];
33     }
34     if(j == tlen)
35         return i - tlen;
36     else
37         return -1;
38 }
39 
40 int main()
41 {
42     cin>>S>>T;
43     slen = strlen(S);
44     tlen = strlen(T);
45     cout<<KMP_Index()+1<<endl;
46     return 0;
47 }

 

posted on 2017-06-09 17:21  hhhhx  阅读(140)  评论(0编辑  收藏  举报

导航