题解 | #字符串排序#
字符串排序
https://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584
自定义排序
思路见代码注释
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); char[] arr = br.readLine().toCharArray(); // 收集字符串中的字母 List<Character> list = new ArrayList<>(arr.length); for (char c : arr) { if (Character.isLetter(c)) { list.add(c); } } // 将字母按要求排序 list.sort((a, b) -> Character.toLowerCase(a) - Character.toLowerCase(b)); StringBuilder builder = new StringBuilder(); for (int i = 0, j = 0; i < arr.length; i++) { if (Character.isLetter(arr[i])) { // 字母按排好序的拼接 builder.append(list.get(j)); j++; } else { // 非字母直接拼接 builder.append(arr[i]); } } pw.println(builder.toString()); pw.flush(); pw.close(); br.close(); } }