-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTask625B.java
More file actions
78 lines (73 loc) · 2.11 KB
/
Task625B.java
File metadata and controls
78 lines (73 loc) · 2.11 KB
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
77
78
import java.util.*;
public class Task625B {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
char[] text = s.next().toCharArray();
char[] pat = s.next().toCharArray();
//System.out.println(Arrays.toString(kmp(text, pat, lps(pat))));
System.out.println(count(kmp(text, pat, lps(pat))));
}
private static int count(char[] matches) {
//System.out.println(Arrays.toString(matches));
int c = 0;
char p = ' ';
int depth = 0;
for(int i = 0; i < matches.length; i++) {
if(matches[i] == '(') {
c += depth == 0 ? 1 : 0;
depth++;
} else if (matches[i] == ')') {
depth--;
} else if (matches[i] == '|') {
} else if (matches[i] == 'x') {
c++;
}
}
return c;
}
private static char[] kmp(char[] in, char[] p, int[] lps) {
char[] pos = new char[in.length];
int i = 0;
int j = 0;
while (i < in.length) {
if(in[i] == p[j]) {
i++;
j++;
}
if(j == p.length) {
if(j > 1) {
pos[i - j] = (pos[i - j] == ')' ? '|' : '(');
pos[i - 1] = ')';
} else pos[i - 1] = 'x';
j = 0;//lps[j - 1];
} else if(i < in.length && in[i] != p[j]) {
if(j != 0)
j = lps[j - 1];
else
i++;
}
}
return pos;
}
private static int[] lps(char[] in) {
int[] lps = new int[in.length];
lps[0] = 0;
int i = 1;
int len = 0;
while(i < in.length) {
if(in[i] == in[len]) {
len++;
lps[i] = len;
i++;
} else {
if(len != 0) {
len = lps[len - 1];
} else {
lps[i] = 0;
i++;
}
}
}
return lps;
}
}