-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLongest prefix suffix
47 lines (41 loc) · 1.09 KB
/
Longest prefix suffix
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
//Longest prefix suffix
import java.io.*;
import java.util.*;
class GFG {
public static void main(String args[]) throws IOException {
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(read.readLine());
while(t-- > 0) {
String s = read.readLine();
Solution ob = new Solution();
System.out.println(ob.longestPrefixSuffix(s));
System.out.println("~");
}
}
}
class Solution {
int longestPrefixSuffix(String s) {
int n = s.length();
int[] lps = new int[n];
int len = 0;
lps[0] = 0;
int i = 1;
while(i < n) {
if(s.charAt(i) == s.charAt(len)) {
len++;
lps[i] = len;
i++;
}
else {
if(len != 0) {
len = lps[len - 1];
}
else {
lps[i] = 0;
i++;
}
}
}
return lps[n - 1];
}
}