题解 | #字符串排序#

字符串排序

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

散列表方法,将相同(a,A)的字符串添加到一个队列上,并将char数组的当前位置置为0
再将数组散列表遍历,重新赋值到char数组,最后将char数组转为字符串
菜鸟方法......

import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;

public class Main{
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        String str = scan.nextLine();

        ConcurrentLinkedQueue<Character>[] ls = new ConcurrentLinkedQueue[27];
        char[] chars = str.toCharArray();
    //将所有字符添加到散列表中
        for(int i = 0;i < chars.length;i++){
            char c = chars[i];
            int subtracted;
            if(c >= 65 && c <= 90){
                subtracted = 65;
            }else if(c >= 97 && c<= 122){
                subtracted = 97;
            }else{
                continue;
            }
            if(ls[c - subtracted] == null ){
                ls[c - subtracted] = new ConcurrentLinkedQueue<>();
            }
            ls[c - subtracted].offer(c);
            chars[i] = 0;
        }
        int j = 0;
        //将排好的字符依次添加到原数组中
        for (ConcurrentLinkedQueue<Character> l : ls) {
            if(l == null) continue;
            for(char c : l){
                while (chars[j] != 0) {
                    j++;
                }
                if(chars[j] == 0){
                    chars[j++] = c;
                }
            }
        }
        System.out.println(new String(chars));
    }
} 


全部评论

相关推荐

不愿透露姓名的神秘牛友
02-12 18:14
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务