这是我的作业:
如果它们非空并且它们的第一个字符是相同的,我们会说2个字符串“匹配”。循环然后返回给定的非空字符串数组,如下所示:如果字符串与数组中的早期字符串匹配,则交换数组中的2个字符串。当交换数组中的位置时,它不再匹配任何内容。使用地图,这可以解决只需一次通过阵列。
allSwap(["ab", "ac"]) → ["ac", "ab"] allSwap(["ax", "bx", "cx", "cy", "by", "ay", "aaa", "azz"]) → ["ay", "by", "cy", "cx", "bx", "ax", "azz", "aaa"] allSwap(["ax", "bx", "ay", "by", "ai", "aj", "bx", "by"]) → ["ay", "by", "ax", "bx", "aj", "ai", "by", "bx"]
答案 0 :(得分:1)
在地图中,将第一个字母存储为键,将最新的键索引存储为值。如果地图中不存在字母,请将其添加到地图中。当地图中已存在字母时,将其从地图中删除并与该索引交换。
/**
* Swaps strings in the array that have the same first letter,
* reading left to right. Once a string has been swapped,
* it will not be swapped again. The input array will be mutated.
*
* @param strings the strings to perform swaps from
* @return the strings after swapping
*/
public static String[] allSwap(final String[] strings) {
// map of first characters, and the index where they were last seen
final Map<Character, Integer> potentialSwap = new HashMap<>();
for (int thisIndex = 0; thisIndex < strings.length; thisIndex++) {
if (strings[thisIndex].isEmpty()) {
continue; // skip empty strings
}
final Character firstChar = strings[thisIndex].charAt(0); // box charAt(0)
// remove firstChar from the map. If it's not found, returns null
final Integer potentialIndex = potentialSwap.remove(firstChar);
if (potentialIndex != null) {
final int thatIndex = potentialIndex; // unbox potentialIndex
// swap values at thisIndex and thatIndex
final String temp = strings[thatIndex];
strings[thatIndex] = strings[thisIndex];
strings[thisIndex] = temp;
} else {
// save the index for possible swapping later
potentialSwap.put(firstChar, thisIndex); // box thisIndex
}
}
return strings;
}
答案 1 :(得分:0)
public String[] allSwap(String[] strings) {
// map of first characters, and the index where they were last seen
Map<Character, Integer> map = new HashMap();
for (int i = 0; i < strings.length; i++) {
char firstChar = strings[i].charAt(0);
// box charAt(0)
// remove firstChar from the map. If it's not found, returns null
Integer removedIndex = map.remove(firstChar);
if (removedIndex != null) {
int j = removedIndex;
// unbox potentialIndex
// swap values at thisIndex and thatIndex
String temp = strings[j];
strings[j] = strings[i];
strings[i] = temp;
} else {
// save the index for possible swapping later
map.put(firstChar, i);
}
}
return strings;
}
答案 2 :(得分:0)
这也可以工作!
public String[] allSwap(String[] strings) {
Map<String,Integer> map = new HashMap<String,Integer>();
for(int i=0;i<strings.length;i++){
if(!map.containsKey(strings[i].substring(0,1))){
map.put(strings[i].substring(0,1),i);
}
else{
String temp = strings[map.get(strings[i].substring(0,1))];
strings[map.get(strings[i].substring(0,1))] = strings[i];
strings[i] = temp;
map.remove(strings[i].substring(0,1));
}
}
return strings;
}