[英]Is there a Comparator to “naturally” sort strings that may contain numbers, guava?
[英]sort array of strings that contain numbers
我今天有一個面試練習:
返回一個排序數組(不區分大小寫)。 排序后的數組將被排序
* 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;
}
您能告訴我我的代碼有什么問題嗎? 謝謝
您的比較邏輯顯然不符合您的規格。 它完全忽略前三個字符,並忽略前三個字符后的數字之后的所有內容。 顯然,您需要考慮以下因素,否則您將永遠無法符合規格:
public int compare(String o1, String o2) {
String s1 = o1.substring(0, 3);
String s2 = o2.substring(0, 3);
if(!s1.equals(s2)) {
return s1.compareTo(s2);
}
String[] fields1 = o1.substring(3).split("[^0-9]", 2);
String[] fields2 = o2.substring(3).split("[^0-9]", 2);
int i1 = Integer.parseInt(fields1[0]);
int i2 = Integer.parseInt(fields2[0]);
if(i1 != i2) {
return i1 - i2;
}
String r1 = "";
if(fields1.length > 1) {
r1 = fields1[1];
}
String r2 = "";
if(fields2.length > 1) {
r2 = fields2[1];
}
return r1.compareTo(r2);
}
這將符合您的規格。 我測試了獲得以下輸出:
AIR1
AIR1Z
AIR2 A
AIR10ab
AIR20AB
AIR20b
AIR111
BIR5A
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.