题解 | #字符串排序#
字符串排序
http://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584
思路:
1.把正常字符和非正常字符(是否是字母)分开处理。
2.正常字符放入list集合,准备排序。
3.非正常字符放入对应位置的char数组中。
4.最后遍历char数组,如果当前char为'\u0000'表示为空,则输出list集合的char,并将下标后移,否则输出char数组的值。
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 input=in.nextLine();
char[] chars=new char[input.length()];
ArrayList<Character> list=new ArrayList<>();
for(int i=0;i<input.length();i++){
if(!vertify(input.charAt(i))){//非字母直接放入对应位置的数组
chars[i]=input.charAt(i);
}else{//字母放入list集合
list.add(input.charAt(i));
}
}
//字母排序
Collections.sort(list,new Comparator<Character>(){
@Override
public int compare(Character c1,Character c2){
if(c1>='a'){
c1=(char)(c1-32);
}
if(c2>='a'){
c2=(char)(c2-32);
}
return c1-c2;
}
});
int j=0;
//输出
for(int i=0;i<chars.length;i++){
if(chars[i]=='\u0000'){//chars[i]为空
System.out.print(list.get(j++));
}else{
System.out.print(chars[i]);
}
}
System.out.println();
}
}
//判断字符是否是字母
public static boolean vertify(char ch){
if((ch>='A' && ch<='Z') || (ch>='a'&&ch<='z')){
return true;
}
return false;
}
}

查看14道真题和解析