题解 | 字符串排序
字符串排序
https://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s = in.nextLine();
char[] charArray = s.toCharArray();
List<Pair> characterList = new ArrayList<>();
// add all the characters and its index into the characterList
for(int i = 0;i<charArray.length;i++){
if(Character.isAlphabetic(charArray[i])){
Pair currentPair = new Pair(i, Character.toLowerCase(charArray[i]));
characterList.add(currentPair);
}
}
// sort the characterList based on value
characterList.sort(Comparator.comparing(p -> p.value));
// print the sorted list according to the original character in the reading string
int index = 0;
for(int i=0;i<s.length();i++){
if(Character.isAlphabetic(s.charAt(i))){
System.out.print(s.charAt(characterList.get(index).index));
index++;
}else{
System.out.print(s.charAt(i));
}
}
}
}
class Pair{
public int index;
public char value;
Pair(int index, char value){
this.index = index;
this.value = value;
}
}
以Pair形式存储每一个字符的原始下标和小写值到一个List,然后sort这个List,然后根据原始string一一输出即可
汤臣倍健公司氛围 420人发布
查看7道真题和解析