题解 | #字符串排序#
字符串排序
https://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584
利用List集合的sort方法,插入排序,可保证大小相同的情况下,顺序是原来的顺序。
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 str = in.nextLine(); HashMap<Integer, String> hm = new HashMap<>(); ArrayList<Character> list = new ArrayList<>(); for(int i=0; i<str.length(); i++){ String s = str.charAt(i) + ""; if(s.matches("[^a-zA-Z]")){ hm.put(i, s); }else{ list.add(str.charAt(i)); } } // 插入排序,如果两个值相同,那么后面的会排在后面。不会影响原来的排序 list.sort((o1,o2) ->{ return (o1+"").toUpperCase().charAt(0) - (o2+"").toUpperCase().charAt(0); }); StringBuffer result = new StringBuffer(); int listIndex = 0; for(int i=0;i<list.size()+hm.size();i++){ if(hm.keySet().contains(i)){ result.append(hm.get(i)); }else{ result.append(list.get(listIndex)); listIndex++; } } System.out.println(result); } } }