题解 | #字符串排序#
字符串排序
http://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584
首先遍历字符串,把不是字母的字符存到答案数组里,是字母的添加到list集合里,并且暂时在数组里保存字母a,利于后面排序后替换。自定义字母的交换算法(如果小写,权值也按大写来算)
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNextLine()) { ArrayList<Character> list = new ArrayList<>();//记录字母 //ArrayList<Character> temp = new ArrayList<>(); String s = in.nextLine(); int n = s.length(); char[] ans = new char[n]; for (int i = 0; i < n; i++) { char ch = s.charAt(i); if(! Character.isLetter(ch)){//不是字母顺序不变 ans[i] = ch; }else{//是字母,用list装起来,并且先装进去字母,后面替换 list.add(ch); ans[i] = 'a'; } } for (int i = 0; i < list.size(); i++) { for (int j = 0; j < list.size()-1-i; j++) { char ch1 = Character.isUpperCase(list.get(j)) ? list.get(j) : Character.toUpperCase(list.get(j)); char ch2 = Character.isUpperCase(list.get(j+1)) ? list.get(j+1) : Character.toUpperCase(list.get(j+1)); if(ch1 > ch2){ char temp = list.get(j); list.set(j,list.get(j+1)) ; list.set(j+1,temp) ; } } } int index = 0; StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { if(ans[i] == 'a'){ ans[i] = list.get(index++); } sb.append(ans[i]); } System.out.println(sb.toString()); } } }