题解 | #字符串排序#
字符串排序
https://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String input = in.nextLine();
// 保存需要排序的字母
List<Character> sortedLetterList = new ArrayList<>();
// 保存不需要排序的非字母(该字符的索引->该字符)
Map<Integer, Character> nonSortedLetterMap = new HashMap<>();
char[] inputs = input.toCharArray();
for (int i = 0; i < inputs.length; i++) {
char c = inputs[i];
// 如果是字母
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
sortedLetterList.add(c);
} else { // 如果不是字母
nonSortedLetterMap.put(i, c);
}
}
// 将字母排序
sortedLetterList.sort((c1, c2) -> {
// 计算排序指标(对应的大写字母的asc码值)
int s1 = c1 < 'a' ? c1 : c1 - 'a' + 'A';
int s2 = c2 < 'a' ? c2 : c2 - 'a' + 'A';
// 当排序指标相等时,按照插入顺序输出
return s1 - s2;
});
int x = 0;
// 打印结果
for (int i = 0; i < inputs.length; i++) {
if (nonSortedLetterMap.containsKey(i)) { // 如果当前位置不是字母
System.out.print(nonSortedLetterMap.get(i)); // 打印非字母字符
x++;
} else {
System.out.print(sortedLetterList.get(i - x)); // 打印字母
}
}
System.out.println();
}
}
#哈希表#
