规则 1 :英文字母从 A 到 Z 排列,不区分大小写。
规则1的意思就是排序
规则 2 :同一个英文字母的大小写同时存在时,按照输入顺序排列。
规则2的意思就是排序算法是稳定的
规则 3 :非英文字母的其它字符保持原来的位置。
规则3的意思就是排序时跳过这些字符
这里我选择了简单的插入排序来实现字符串排序 也可以选择其他的稳定排序算法 看个人喜好
import java.util.Arrays;
import java.util.Scanner;
import static java.lang.Character.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char[] chars = in.nextLine().toCharArray();
for (int i = 0; i < chars.length; i++) {
for (int j = i; j > 0; ) {
int fst = lastLetterIndex(chars, j);
int snd = lastLetterIndex(chars, fst - 1);
j = fst - 1;
if (fst != -1 && snd != -1 && toUpperCase(chars[fst]) < toUpperCase(chars[snd])) {
swap(chars, fst, snd);
} else {
break;
}
}
}
System.out.println(String.valueOf(chars));
}
static void swap(char[] chars, int idx1, int idx2) {
if (idx1 == idx2) {
return;
}
char temp = chars[idx1];
chars[idx1] = chars[idx2];
chars[idx2] = temp;
}
static int lastLetterIndex(char[] arr, int a) {
if (a < 0) {
return -1;
}
if (isLetter(arr[a])) {
return a;
}
for (int i = a - 1; i >= 0; i--) {
if (isLetter(arr[i])) {
return i;
}
}
return -1;
}
}
看了热门题解 改了一下
import java.util.*;
import java.util.stream.*;
import static java.lang.Character.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
String sortedLetters = Stream.of(str.split(""))
.filter(x -> isLetter(x.charAt(0)))
.sorted(Comparator.comparing(String::toUpperCase))
.reduce((x, y) -> x + y)
.orElse(null);
int i = 0;
StringBuilder sb = new StringBuilder();
for (char c : str.toCharArray()) {
if (!isLetter(c)) {
sb.append(c);
} else {
sb.append(sortedLetters.charAt(i++));
}
}
System.out.println(sb);
}
}

京公网安备 11010502036488号