题解 | #字符串排序#
字符串排序
http://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584
先存入list排序,用另一个list记录非字母下表,然后再插入
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
String str = sc.nextLine();
char[] chars = str.toCharArray();
System.out.println(sort(chars));
}
}
public static StringBuilder sort(char[] chars){
// 用于记录非字母下标
List<Integer> indexList = new ArrayList<>();
List<Character> listChars= new ArrayList<>();
for(int i=0;i<chars.length;i++){
if(Character.isLetter(chars[i])){
listChars.add(chars[i]);
}else{
indexList.add(i);
}
}
// 字母排序
Collections.sort(listChars, new Comparator<Character>() {
@Override
public int compare(Character o1, Character o2) {
return Character.toLowerCase(o1)-Character.toLowerCase(o2);
}
});
StringBuilder builder = new StringBuilder();
for (Character listChar : listChars) {
builder.append(listChar);
}
for (Integer integer : indexList) {
// 插入非字母
builder.insert(integer,String.valueOf(chars[integer]));
}
return builder;
}
}