Find all palindrome present in a given string.
String = aabacdcxyyz, palindrome - [aa, aba, cdc, yy]
To get it using 2 for loops first will run from 0 to length of string and 2nd will run from 0 to first for loop current position(i).
Using second loop get all the substring from string for all the index from 0 to i and reverse that and check if both are equals so add them to a list and then return the list.
public class AllPalindrom {
public static void main(String[] args) {
String str = "aabacdcxyyz";
System.out.println(getPalindrom(str));
}
private static ArrayList<String> getPalindrom(String str) {
ArrayList<String> list = new ArrayList<>();
for(int i=0;i<str.length();i++){
for(int j=0;j<=i;j++){
String temp = str.substring(j,i);
if(temp.length()>1 &&
temp.equals(String.valueOf(new StringBuilder(temp).reverse()))){
list.add(temp);
}
}
}
//System.out.print(list);
return list;
}
}
String = aabacdcxyyz, palindrome - [aa, aba, cdc, yy]
To get it using 2 for loops first will run from 0 to length of string and 2nd will run from 0 to first for loop current position(i).
Using second loop get all the substring from string for all the index from 0 to i and reverse that and check if both are equals so add them to a list and then return the list.
public class AllPalindrom {
public static void main(String[] args) {
String str = "aabacdcxyyz";
System.out.println(getPalindrom(str));
}
private static ArrayList<String> getPalindrom(String str) {
ArrayList<String> list = new ArrayList<>();
for(int i=0;i<str.length();i++){
for(int j=0;j<=i;j++){
String temp = str.substring(j,i);
if(temp.length()>1 &&
temp.equals(String.valueOf(new StringBuilder(temp).reverse()))){
list.add(temp);
}
}
}
//System.out.print(list);
return list;
}
}