File tree Expand file tree Collapse file tree 1 file changed +64
-0
lines changed
Expand file tree Collapse file tree 1 file changed +64
-0
lines changed Original file line number Diff line number Diff line change 1+ ``` java
2+ import java.io.* ;
3+ import java.util.* ;
4+
5+ public class Main {
6+
7+
8+ static int [] failure;
9+ static int count = 0 ;
10+ public static void main (String [] args ) throws Exception {
11+ BufferedReader br = new BufferedReader (new InputStreamReader (System . in));
12+
13+
14+ String a = br. readLine();
15+ a += a. substring(0 , a. length() - 1 );
16+ String b = br. readLine();
17+
18+ char [] ac = a. toCharArray();
19+ char [] bc = b. toCharArray();
20+
21+ failure = new int [ac. length];
22+
23+ failureFunction(bc);
24+ kmp(ac, bc);
25+ System . out. println(count);
26+ }
27+
28+ public static void failureFunction (char [] s ) {
29+ int p = 0 ;
30+
31+ for (int idx = 1 ; idx < s. length; idx++ ) {
32+
33+ while (p != 0 && s[idx] != s[p]) {
34+ p = failure[p - 1 ];
35+ }
36+
37+ if (s[idx] == s[p]) {
38+ p++ ;
39+ failure[idx] = p;
40+ }
41+ }
42+
43+ }
44+
45+ public static void kmp (char [] s1 , char [] s2 ) {
46+
47+ int p = 0 ;
48+
49+ for (int idx = 0 ; idx < s1. length; idx++ ) {
50+
51+ while (p != 0 && s1[idx] != s2[p]) p = failure[p - 1 ];
52+
53+ if (s1[idx] == s2[p]) {
54+ if (p == s2. length - 1 ) {
55+ count++ ;
56+ p = failure[p];
57+ } else {
58+ p++ ;
59+ }
60+ }
61+ }
62+ }
63+ }
64+ ```
You can’t perform that action at this time.
0 commit comments