Neon
BAN USERJava Streams makes it easy to check that at most one character appears an odd number of times
public class Palindrome {
public static void main(String[] args) {
String word = "ghijjihkkgg";
String[] split = word.split("");
Arrays.sort(split);
Map<String, Integer> result = Arrays.stream(split)
.collect(Collectors.groupingBy((String s) -> s))
.values().stream()
.collect(Collectors.toMap((list) -> (String) list.get(0), (list) -> list.size()));
if (result.values().stream().filter(i -> (i & 0x1) == 1).count() > 1) {
System.out.println("No palindrome ");
} else {
StringBuffer prefix = new StringBuffer();
String center = "";
for (Map.Entry<String, Integer> e : result.entrySet()) {
String c = e.getKey();
for (int i = 0; i < e.getValue() / 2; i++) {
prefix.append(c);
}
if ((e.getValue() & 0x1) == 1) {
center = c;
}
}
StringBuffer palindrome = new StringBuffer().append(prefix).append(center);
prefix.reverse();
palindrome.append(prefix);
System.out.println("Palindrome of " + word + " is " + palindrome);
}
}
}
Oops, ignore the Arrays,sort() that was a leftover and is not necessary
- Neon September 14, 2015