There was some online test where I was asked about finding all possible distinct palindromes of a string.
Here I had to give the count of all possible distinct palindromes of a given string (continuous substring). Here, a single character word is considered a palindrome.
Below is what I did. Can you please tell me if it is good OR there is a scope of improvement?
public class Solution {
/*
* Complete the function below.
*/
static int palindrome(String str) {
String[] strArray = str.split("");
List<String> list = Arrays.asList(strArray);
list = list.subList(1, list.size());
//Set does'nt allow duplicates.
//Sublist is required because split method gives an extra space.
Set<String> palindromeSet = new HashSet<>(list);
String palindromeStr = null;
for(int i = 0;i<list.size();i++){
palindromeStr = list.get(i);
for(int j = i+1;j<list.size();j++){
palindromeStr = palindromeStr+list.get(j);
if(isPalindrome(palindromeStr)){
palindromeSet.add(palindromeStr);
}
}
}
return palindromeSet.size();
}
static boolean isPalindrome(String str){
char[] chars = str.toCharArray();
for(int i =0;i<(chars.length/2);i++){
if(chars[i] != chars[chars.length-1-i]){
return false;
}
}
return true;
}
public static void main(String[] args) throws IOException{
System.out.println(palindrome("arewenotdrawnonwardtonewera"));
}
}