Recent day interviews you may faced this question in programing interview. Find the sub string palindrome of given string input.
We have many way to solve it. Here I added coding snippet which I tried to solve it.
First one I used two for loop to solve it. Its very simple and easy.
private static List<String> subStringPalindrome(String value) {
List<String> list = new ArrayList<>();
for(int i =0 ; i < value.length(); i++){
for(int j = i+1 ; j < value.length(); j++){
StringBuffer s1 = new StringBuffer(value.substring(i,j));
String s2 = s1.reverse().toString();
if(value.substring(i,j).contentEquals(s2) && s1.length()> 1){
list.add(s1.toString());
}
}
}
return list;
}
List<String> list = subStringPalindrome("eetestseeammadam");Output: [ee, ete, estse, sts, ee, amma, mm, ada]Its very simple and easy. This code look simple and easy and I tried another way using recursion.
private static List<String> printPalindromeSubString(String value;) {
List<String> list = new ArrayList<>();
if(value.equals(new StringBuilder(value).reverse()))
list.add(value);
for(int i=0; i <= value.length(); i++){
if(i > 1 && i < value.length() -1){
StringBuffer reverse = new StringBuffer(value.substring(i-2, i+1));
if(value.substring(i-2, i+1).contentEquals(reverse.reverse())){
System.out.println("Called2");
list.add(value.substring(i-2, i+1));
if(i>2){
if(i+2 <= value.length()){
new Test().callRecursion(value,value.substring(i-2, i+1), i-1, i, list );
}
}
}
}
if(i > 0 && i < value.length() ){
StringBuffer stringBuffer = new StringBuffer(value.substring(i-1, i+1));
if(value.substring(i-1, i+1).contentEquals(stringBuffer.reverse())){
list.add(value.substring(i-1, i+1));
System.out.println("Called");
if(i > 1){
new Test().callRecursion(value,value.substring(i-1, i+1), i, i, list );
}
}
}
}
return list;
}
private List<String> callRecursion(String value, String reversed, int i, int j, List<String> list){
if(j+1 >= value.length())
return list;
else if(value.charAt(i-2) == value.charAt(j+1)){
String s = value.charAt(i-2) +reversed+ value.charAt(j+1);
list.add(s);
callRecursion(value, s, i-1, j+1, list);
}
System.out.println(list);
return list;
}List<String> list = printPalindromeSubString("eetestseeammadam");Here i used recursion to find palindrome on given substring. And the output is
[ee, ete, sts, estse, ee, mm, amma, ada, madam]
And the output is If you check the output from two logic, there is a mismatch.. First one print only 8 palindrome and recursion logic print 9 palindrome. 'madam' missing in first logic.
Lets make this blog more interactive with techies, Please find the missing condition or part of code on comment area.✌✌
Thanks in advance.
No comments:
Post a Comment