题解 | #字符串排序#
字符串排序
https://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584?tpId=37&rp=1&ru=%2Fexam%2Fcompany&qru=%2Fexam%2Fcompany&sourceUrl=%2Fexam%2Fcompany&difficulty=&judgeStatus=&tags=&title=&gioEnter=menu
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String s = in.nextLine(); //Mapping:字符->出现index ArrayList<Map.Entry<Character, Integer>> list = new ArrayList<>(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (Character.isLetter(c)) { list.add(new AbstractMap.SimpleEntry<>(c, i)); //加入元素 } } list.sort((o1, o2)-> { //排序 char c1 = o1.getKey(), c2 = o2.getKey(); if (c1 <= 'z' && c1 >= 'a') c1 = (char)(c1 - 32); if (c2 <= 'z' && c2 >= 'a') c2 = (char)(c2 - 32); return c1 == c2 ? o1.getValue() - o2.getValue() : c1 - c2; //如果两者大写都相等,就按照先后顺序,如果不是同一个字母就按照字母表顺序 }); char[] charArray = s.toCharArray(); //把字符替换进去 for (int i = 0; i < charArray.length; i++) { if (Character.isLetter(charArray[i])) { charArray[i] = list.get(0).getKey(); list.remove(0); } } System.out.println(String.valueOf(charArray)); } }
使用List+Map.Entry