题解 | #字符串排序#
字符串排序
https://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584
先取出所有英文字母,用冒泡排序进行排序,因为冒泡排序是稳定的,不改变值相同的元素的相对位置
然后StringBuilder保存结果,不是字母的直接添加,是字母的用排好序的list添加
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
char[] charArray = s.toCharArray();
ArrayList<Character> list = new ArrayList<>();
for (char c : charArray) {
if (Character.isLetter(c)) {
list.add(c);
}
}
//冒泡排序不改变值相同的元素的相对位置
for (int i = 0; i < list.size() - 1; i++) {
for (int j = 0; j < list.size() - 1 - i; j++) {
char c1 = list.get(j);
char c2 = list.get(j + 1);
//j是大写,j+1是小写
if ((c1 >= 'A' && c1 <= 'Z') && (c2 >= 'a' && c2 <= 'z')) {
if (c1 + 32 > c2) {
list.set(j + 1, c1);
list.set(j, c2);
}
}
//j是小写,j+1是大写
else if ((c2 >= 'A' && c2 <= 'Z') && (c1 >= 'a' && c1 <= 'z')) {
if (c1 > c2 + 32) {
list.set(j + 1, c1);
list.set(j, c2);
}
}
//j和j+1都是大写或者都是小写
else {
if (c1 > c2) {
list.set(j + 1, c1);
list.set(j, c2);
}
}
}
}
int j = 0;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < charArray.length; i++) {
if (!Character.isLetter(charArray[i])) {
sb.append(charArray[i]);
} else sb.append(list.get(j++));
}
System.out.println(sb);
}
}
查看2道真题和解析