hdu 2203 亲和串 KMP

亲和串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/** Sep 8, 2015 10:56:55 PM
* PrjName:hdu2203
* @author Semprathlon
*/
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
InputReader in=new InputReader(System.in);
PrintWriter out=new PrintWriter(System.out);
while(in.nextLine()!=null){
String s=in.next();
s=new String(s+s);
String t=in.next();
out.println(KMP.Index(s, t)>-1?"yes":"no");
}
out.flush();
out.close();
}

}
class KMP{
static int next[];
static void getNext(String T){
next=new int[T.length()+1];
int j = 0, k = -1; next[0] = -1;
while(j < T.length())
if(k == -1 || T.charAt(j) == T.charAt(k))
next[++j] = ++k;
else
k = next[k];
}
static int Index(String S,String T)
{
int i = 0, j = 0;
getNext(T);

for(i = 0; i < S.length()&&j<T.length(); i++)
{
while(j > 0 && S.charAt(i) != T.charAt(j))
j = next[j];
if(S.charAt(i) == T.charAt(j))
j++;
}
if(j == T.length())
return i - T.length();
else
return -1;
}
static int Count(String S,String T)
{
int res = 0,j=0;
if(S.length() == 1 && T.length() == 1)
{
if(S.charAt(0) == T.charAt(0))
return 1;
else
return 0;
}
getNext(T);
for(int i = 0; i < S.length(); i++)
{
while(j > 0 && S.charAt(i) != T.charAt(j))
j = next[j];
if(S.charAt(i) == T.charAt(j))
j++;
if(j == T.length())
{
res++;
j = next[j];
}
}
return res;
}
}
Author

Semprathlon / Simfae Dean

Posted on

09/08/2015

Updated on

07/19/2023

Licensed under

Comments