fork download
  1.  
  2. import java.util.Map;
  3. import java.util.HashMap;
  4. import java.util.Arrays;
  5.  
  6. public class Main {
  7. public static void main (String[] args) {
  8. String[] arr = {"ax", "bx", "cx", "cy", "by", "ay", "aaa", "azz"};
  9. System.out.println(Arrays.toString(allSwap(arr)));
  10. }
  11.  
  12. /**
  13. * Swaps strings in the array that have the same first letter,
  14. * reading left to right. Once a string has been swapped,
  15. * it will not be swapped again. The input array will be mutated.
  16. *
  17. * @param strings the strings to perform swaps from
  18. * @return the strings after swapping
  19. */
  20. public static String[] allSwap(final String[] strings) {
  21. // map of first characters, and the index where they were last seen
  22. final Map<Character, Integer> potentialSwap = new HashMap<>();
  23.  
  24. for (int thisIndex = 0; thisIndex < strings.length; thisIndex++) {
  25. if (strings[thisIndex].isEmpty()) {
  26. continue; // skip empty strings
  27. }
  28.  
  29. final Character firstChar = strings[thisIndex].charAt(0); // box charAt(0)
  30. // remove firstChar from the map. If it's not found, returns null
  31. final Integer potentialIndex = potentialSwap.remove(firstChar);
  32.  
  33. if (potentialIndex != null) {
  34. final int thatIndex = potentialIndex; // unbox index
  35. // swap values at thisIndex and thatIndex
  36. final String temp = strings[thatIndex];
  37. strings[thatIndex] = strings[thisIndex];
  38. strings[thisIndex] = temp;
  39. } else {
  40. // save the index for possible swapping later
  41. potentialSwap.put(firstChar, thisIndex); // box thisIndex
  42. }
  43. }
  44.  
  45. return strings;
  46. }
  47. }
Success #stdin #stdout 0.04s 711168KB
stdin
Standard input is empty
stdout
[ay, by, cy, cx, bx, ax, azz, aaa]