题解 | #字符串排序#
字符串排序
https://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main{ public static void main(String[] args) throws IOException{ Scanner sc = new Scanner(System.in); String str = sc.next(); List<Character> letters = new ArrayList<>(); for(char ch: str.toCharArray()){ if (Character.isLetter(ch)) { letters.add(ch); } } letters.sort(new Comparator<Character>() { public int compare(Character o1, Character o2) { return Character.toLowerCase(o1) - Character.toLowerCase(o2); } }); StringBuffer sb = new StringBuffer(); int j = 0; for(int i = 0; i < str.length(); i++){ if(Character.isLetter(str.charAt(i))){ sb.append(letters.get(j++)); } else{ sb.append(str.charAt(i)); } } System.out.println(sb.toString()); } }
核心点:
1.判断是否为字母
Character.isLetter()2.将字母大写转为小写
Character.toLowerCase(o1)3.
Comparator是稳定的排序,即如果return 0,不会改变两个字母的顺序