题解 | #字符串排序#
字符串排序
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.hasNextLine()) { // 注意 while 处理多个 case String a = in.nextLine(); char[] cArr = a.toCharArray(); List<Character> cList = new ArrayList<>(); Map<Integer,Character> notLetterMap=new HashMap<>(); for (int i = 0; i < a.length(); i++) { char cCur = cArr[i]; //不是字母存在hashMap中 if (!isLetter(cCur)) { notLetterMap.put(i,cCur); continue; } //是字母 //第一个字母无需比较 if (cList.isEmpty()) { cList.add(cCur); continue; } //子循环中cList不存放非字符 for (int j = 0; j < cList.size(); j++) { char cListCur = cList.get(j); //例子cCur='a' cList.get(j)='b' 将a放在cList的当前位置b往后顺延 if (letterDiff(cCur, cListCur) < 0) { cList.add(j, cCur); //值放入跳出子循环 break; } //例子cCur='b' cList.get(j)='a' 往后顺延 if (letterDiff(cCur, cListCur) > 0) { if (j == cList.size() - 1) { cList.add(cList.size(), cCur); break; } continue; } if (isSameLetter(cCur, cListCur)) { if (j == cList.size() - 1) { cList.add(cList.size(), cCur); break; } continue; } } } notLetterMap.keySet().stream().sorted().forEach(i->cList.add(i,notLetterMap.get(i))); cList.forEach(s->System.out.print(s)); } } static int letterDiff(char a, char b) { return Character.toLowerCase(a) - Character.toLowerCase(b); } static boolean isSameLetter(char a, char b) { return letterDiff(a, b) == 0; } static boolean isLetter(char c) { return (c >= 'a' && c <='z') || (c >= 'A' && c <= 'Z'); } }