今日は面接の練習があります。
return ソートされた配列 (大文字と小文字を区別しない)。ソートされた配列がソートされます
* alphabetically by the first 3 characters, then numerically by
* the following number and then alphabetically by the remaining characters with
* spaces above characters.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import org.junit.Test;
public class MySort {
public String[] testSortArray(String[] input){
// TODO: Sort the array
}
@Test
public void testSort() {
String[] input = new String[8];
input[0] = "AIR1";
input[1] = "AIR20b";
input[2] = "BIR5A";
input[3] = "AIR20AB";
input[4] = "AIR10ab";
input[5] = "AIR2 A";
input[6] = "AIR111";
input[7] = "AIR1Z";
MySort sortTest = new MySort();
String[] output = sortTest.testSortArray(input);
String[] expected = new String[8];
expected[0] = "AIR1";
expected[1] = "AIR1Z";
expected[2] = "AIR2 A";
expected[3] = "AIR10ab";
expected[4] = "AIR20AB";
expected[5] = "AIR20b";
expected[6] = "AIR111";
expected[7] = "BIR5A";
assertEquals(Arrays.asList(output), Arrays.asList(expected));
for (String item : output) {
System.out.println(item);
}
}
}
私は testSortArray(String[] 入力を次のように実装しました:
public String[] testSortArray(String[] input){
Collections.sort(Arrays.asList(input), new Comparator<String>() {
public int compare(String o1, String o2) {
return extractNumber(o1) - extractNumber(o2);
}
int extractNumber(String s) {
String num = s.replaceAll("\\D", "");
// return 0 if no digits found
return num.isEmpty() ? 0 : Integer.parseInt(num);
}
});
return input;
}
私のコードで何が間違っているのか教えてください。ありがとう