mail2abin
BAN USERThis code does not compile. But if assuming this code
private static String noRepeatingChars(String input) {
Map<Character, Integer> histogram = new LinkedHashMap<Character, Integer>();
char[] chars = input.toCharArray();
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if (histogram.containsKey(c)) {
histogram.put(c, histogram.get(c) + 1);
} else {
histogram.put(c, 1);
}
}
String output = "";
Character prevChar = null;
while (!histogram.isEmpty()) {
Iterator<Map.Entry<Character, Integer>> iterator;
for (iterator = histogram.entrySet().iterator(); iterator.hasNext() ;) {
Map.Entry<Character, Integer> entry = iterator.next();
if (entry.getKey() == prevChar) return "INVALID";
prevChar = entry.getKey();
output = output + prevChar;
entry.setValue(entry.getValue() - 1);
if (entry.getValue() == 0) iterator.remove();
}
}
return output;
}
=========================
Then it fails for "aabbb".
Here is a shorter one in scala...
- mail2abin October 21, 2015def rearrange(input: String): String = {
val list = input.groupBy { x => x }.values.flatten
val k = input.groupBy { x => x }.mapValues { x => x.size }
if (k.values.max > Math.ceil(input.length() / 2.0))
"NA"
else {
val part = k.toSeq.sortWith(_._2 > _._2)
.flatMap { elem => List.fill(elem._2)(elem._1) }
val (x, y) = if (s.length() % 2 == 0) part.splitAt(list.size / 2)
else part.splitAt(list.size / 2 + 1)
val p = ((x zip y).flatMap { x => List(x._1, x._2) }).mkString
if(x.size > y.size)
p + x.head
else p
}
}