-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
b004e85
commit 0414832
Showing
1 changed file
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]; | ||
} | ||
} |