题解 | #字符串排序#
字符串排序
https://www.nowcoder.com/practice/5af18ba2eb45443aa91a11e848aa6723
import java.util.Scanner;
import java.lang.String;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static int wordCompare(String s1, String s2) {
// 0表示相等,大于0表示大于,小于0表示小于
int result = 0;
char[] chars1 = s1.toCharArray();
char[] chars2 = s2.toCharArray();
for (int i = 0; i < Math.min(chars1.length, chars2.length); i++) {
if (chars1[i] > chars2[i]) {
result = 1;
break;
} else if (chars1[i] < chars2[i]) {
result = -1;
break;
}
}
if (result == 0) {
result = chars1.length - chars2.length;
}
return result;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String[] strArr = new String[n];
for (int i = 0; i < n; i++) {
strArr[i] = in.next();
}
// 冒泡排序
for (int i = 0; i < strArr.length - 1; i++) {
for (int j = 0; j < strArr.length - i - 1; j++) {
if (wordCompare(strArr[j], strArr[j + 1]) > 0) {
String s = strArr[j + 1];
strArr[j + 1] = strArr[j];
strArr[j] = s;
}
}
}
for (String str : strArr) {
System.out.println(str);
}
}
}

