Skip to content

Commit

Permalink
Create Longest prefix suffix
Browse files Browse the repository at this point in the history
  • Loading branch information
dishathakurata authored Dec 6, 2024
1 parent b004e85 commit 0414832
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions Longest prefix suffix
Original file line number Diff line number Diff line change
@@ -0,0 +1,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];
}
}

0 comments on commit 0414832

Please sign in to comment.