题解 | #字符串排序#
字符串排序
https://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { String input = sc.nextLine(); String new1 = input.replaceAll("[^a-zA-Z]", ""); String new2 = input.replaceAll("[a-zA-Z]", ""); char[] symbles = new2.toCharArray(); Character[] array1 = new Character[new1.length()]; for (int i = 0; i < new1.length(); i++) { array1[i] = new1.charAt(i); } List<Integer> indexs = new ArrayList<>(); for (int i = 0; i < input.length(); i++) { if (input.substring(i, i+1).matches("[^a-zA-Z]")) { indexs.add(i); } } Arrays.sort(array1, new Comparator<Character>() { @Override public int compare(Character o1, Character o2) { if (o1 >= 'a' && o1 <= 'z') { o1 = (char)(o1 - ('a' - 'A')); } if (o2 >= 'a' && o2 <= 'z') { o2 = (char)(o2 - ('a' - 'A')); } return o1 - o2; } }); int m = 0; int n = 0; char[] charArray = new char[input.length()]; for (int i = 0; i < input.length(); i++) { if (indexs.contains(i)) { charArray[i] = symbles[n]; n++; } else { charArray[i] = array1[m]; m++; } } System.out.println(String.valueOf(charArray)); } } }