题解 | #字符串排序#

字符串排序

https://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584

基数排序

过滤掉字符,进行基数排序,由于要考虑大小写出现的顺序,使用链表记录每一个字符,到时候按序输出即可。

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            String s = in.nextLine();
            
            // 记录字母排序,类似基数排序
            List<List<Character>> buckets = new ArrayList<>();
            for(int i = 0; i < 26; i++) {
                buckets.add(new ArrayList<>());
            }
            char[] str = s.toCharArray();
            for(int i = 0; i < str.length; i++) {
                char ch = str[i];
                if(Character.isLetter(ch))
                    buckets.get(Character.toLowerCase(ch) - 'a').add(ch);
            }

            int buck = 0;
            int buckId = 0;
            for(int i = 0; i < str.length; i++) {
                if(Character.isLetter(str[i])) {
                    while(buckId >= buckets.get(buck).size()) {
                        // 寻找下一个桶
                        buck++;
                        buckId = 0;
                    }

                    // 直接修改数组
                    str[i] = buckets.get(buck).get(buckId++);
                }
            }

            System.out.println(String.valueOf(str));
        }
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-01 17:13
想去,但是听说加班强度实在难崩,所以拒绝了,现在有点心梗对面hr感觉也是实习生,打电话的时候怪紧张的,但是感觉人很好嘞
水中水之下水道的鼠鼠:哥们这不先去体验一下,不行再跑呗,大不了混个实习经历(有更好的转正offer就当我没说)
点赞 评论 收藏
分享
06-07 17:17
嘉兴学院 教师
心爱的idea:你孩
点赞 评论 收藏
分享
每晚夜里独自颤抖:这个在牛客不是老熟人了吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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