eMarcus.G
BAN USERpublic class Palindrome {
public static void main(String []args){
getPalindrome(args);
}
public static String[] getPalindrome(String []args){
Set<String> dictionary = createDictionary();
List<String> palindromes = new ArrayList<>();
for (String word: args)
for (String combination : getCombinations(word))
if (! combination.equals(word))
if (dictionary.contains(combination)){
palindromes.add(combination);
System.out.println(combination);
}
if (palindromes.size() < 1)
System.exit(-1);
return palindromes.toArray(new String[palindromes.size()]);
}
private static Set<String> createDictionary() {
Set<String> dictionary = new HashSet<>();
dictionary.add("art");
dictionary.add("tar");
dictionary.add("rat");
return dictionary;
}
private static List<String> getCombinations(String word) {
List<String> combinations = new ArrayList<>();
if (word.length() <= 1)
return combinations;
if (word.length() == 2)
{ combinations.add(word);
combinations.add( exchg(word));
return combinations;
}
for (int i = 0; i < word.length(); i++)
{
String first = word.substring(0, i);//
String second = word.substring(i+1,word.length());// rt
for (String firstAndSecond: getCombinations( first + second) )
combinations.add(word.charAt(i) + firstAndSecond);
}
return combinations;
}
private static String exchg(String word){
return ""+ word.charAt(1) + word.charAt(0);
}
}
This is a function that converts an array of strings all in lower case to palindrome, it relies on a dictionary. The complexity is O(nm) where n is the number of words and m is the average word length. The dictionary should be in lowercase and should also contain multi-word combinations with apostrophe without the apostrophe. At the end a map for multi-words without apostrophe should be mapped to separate words with apostrophe.
}
- eMarcus.G September 29, 2015