题解 | 字符串排序

字符串排序

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一一输出即可

全部评论

相关推荐

真烦好烦真烦:牛友太有实力了
点赞 评论 收藏
分享
白火同学:大二有这水平很牛了,可以适当对关键信息加粗一点,比如关键技术、性能指标之类的。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务