题解 | #字符串排序#
字符串排序
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); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNext()) { // 注意 while 处理多个 case String str = in.nextLine(); //转成数组 char[] arr = str.toCharArray(); //使用数组的常规排序:避开特殊字符,保持大小写 for (int i = 0; i < arr.length - 1; i++) { for (int j = 0; j < arr.length - i - 1; j++) { String left = Character.toString(arr[j]).toUpperCase(); String right = Character.toString(arr[j + 1]).toUpperCase(); // System.out.println(arr[j] + " " + arr[j + 1]); if (!check(arr[j]) && !check(arr[j + 1])) { if (left.charAt(0) > right.charAt(0)) { char ch = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = ch; } } else if (!check(arr[j]) && check(arr[j + 1])) { int index = j + 1; //继续向后找到非特殊字符 while (index < arr.length && check(arr[index])) { index++; } //不是因为超长退出循环,找到英文字符 if (index != arr.length) { right = Character.toString(arr[index]).toUpperCase(); if (left.charAt(0) > right.charAt(0)) { char ch = arr[j]; arr[j] = arr[index]; arr[index] = ch; } } } } } for (int i = 0; i < arr.length; i++) { System.out.print(arr[i]); } } } public static boolean check(char a) { if (a >= 'a' && a <= 'z' || a >= 'A' && a <= 'Z') { return false; } return true; } }
纯冒泡排序,仅下列条件满足时交换:
a[j] a[j+1] 交换方式
英文字符 非英文字符 j+1作为起点,找到下一个英文字符
英文字符 英文字符 两者均换成大写或小写,进行比较交换