This is my solution to CodingBat problem p150113. My Java knowledge is from 2011 and I'd like to know if this is still the optimal way to approach such a problem. and if my code is clean and understandable.
We'll say that 2 strings "match" if they are non-empty and their first chars are the same. Loop over and then return the given array of non-empty strings as follows: if a string matches an earlier string in the array, swap the 2 strings in the array. A particular first char can only cause 1 swap, so once a char has caused a swap, its later swaps are disabled. Using a map, this can be solved making just one pass over the array.
firstSwap(["ab", "ac"]) → ["ac", "ab"]
firstSwap(["ax", "bx", "cx", "cy", "by", "ay", "aaa", "azz"]) → ["ay", "by", "cy", "cx", "bx", "ax", "aaa", "azz"]
firstSwap(["ax", "bx", "ay", "by", "ai", "aj", "bx", "by"]) → ["ay", "by", "ax", "bx", "ai", "aj", "bx", "by"]
public String[] firstSwap(String[] strings) {
HashMap<String,Integer> hashMap = new HashMap<>();
int counter = 0;
int index = 0;
for (String s : strings){
String firstChar = s.substring(0,1);
if(hashMap.containsKey(firstChar)){
// make the switch in the array
if(hashMap.get(firstChar) > -1){
index = hashMap.get(firstChar);
String temp = strings[counter];
strings[counter] = strings[index];
strings[index] = temp;
// make sure it doesn't get swapped again:
hashMap.put(firstChar,-1);
}
} else {
hashMap.put(firstChar,counter);
}
counter = counter + 1;
}
return strings;
}