Company: MakeMyTrip, Amazon, Accolite
Question:
Question:
Given a string of character, find the length of longest proper prefix which is also a proper suffix.
Example:
S = abab
lps is 2 because, ab.. is prefix and ..ab is also a suffix.
Example:
S = abab
lps is 2 because, ab.. is prefix and ..ab is also a suffix.
Input:
First line is T number of test cases. 1<=T<=100.
Each test case has one line denoting the string of length less than 100000.
First line is T number of test cases. 1<=T<=100.
Each test case has one line denoting the string of length less than 100000.
Expected time compexity is O(N).
Output:
Print length of longest proper prefix which is also a proper suffix.
Print length of longest proper prefix which is also a proper suffix.
Example:
Input:
2
abab
aaaa
Input:
2
abab
aaaa
Output:
2
3
2
3
CODE:
import java.util.*;
import java.lang.*;
import java.io.*;
class Solution{
public static void main (String[] args) {
Scanner sc = new Scanner (System.in);
int m = sc.nextInt();
for(int mi=0;mi<m;mi++){
String s= sc.next();
int i=0, max=0;
for (int j=1;j<s.length();j++){
{if (s.charAt(i)== s.charAt(j))
{i++;}
else{if(i> 0)
j--;
i=0;
}
}
}
System.out.println(Math.max(i,max));
}
}
}
EXECUTION TIME: 0.14s
Comments
Post a Comment