题解 | #字符串排序#

字符串排序

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);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            String  a = in.nextLine();
            char[] cArr = a.toCharArray();
            List<Character> cList = new ArrayList<>();
            Map<Integer,Character> notLetterMap=new HashMap<>();
            for (int i = 0; i < a.length(); i++) {
                char cCur = cArr[i];
                //不是字母存在hashMap中
                if (!isLetter(cCur)) {
                    notLetterMap.put(i,cCur);
                    continue;
                }
                //是字母
                //第一个字母无需比较
                if (cList.isEmpty()) {
                    cList.add(cCur);
                    continue;
                }
                //子循环中cList不存放非字符
                for (int j = 0; j < cList.size(); j++) {
                    char cListCur = cList.get(j);
                    //例子cCur='a' cList.get(j)='b' 将a放在cList的当前位置b往后顺延
                    if (letterDiff(cCur, cListCur) < 0) {
                        cList.add(j, cCur);
                        //值放入跳出子循环
                        break;
                    }
                    //例子cCur='b' cList.get(j)='a' 往后顺延
                    if (letterDiff(cCur, cListCur) > 0) {
                        if (j == cList.size() - 1) {
                            cList.add(cList.size(), cCur);
                            break;
                        }
                        continue;
                    }

                    if (isSameLetter(cCur, cListCur)) {
                        if (j == cList.size() - 1) {
                            cList.add(cList.size(), cCur);
                            break;
                        }
                        continue;
                    }



                }

            }
            notLetterMap.keySet().stream().sorted().forEach(i->cList.add(i,notLetterMap.get(i)));
            cList.forEach(s->System.out.print(s));



        }

    }
    static int letterDiff(char a, char b) {
        return Character.toLowerCase(a) - Character.toLowerCase(b);
    }
    static boolean isSameLetter(char a, char b) {
        return letterDiff(a, b) == 0;
    }
    static boolean isLetter(char c) {
        return (c >= 'a' && c <='z') || (c >= 'A' && c <= 'Z');
    }
}

全部评论

相关推荐

07-14 13:37
重庆大学 C++
点赞 评论 收藏
分享
07-02 22:46
门头沟学院 Java
码农索隆:hr:“管你投没投,先挂了再说”
点赞 评论 收藏
分享
风中翠竹:真的真的真的没有kpi。。。面试官是没有任何kpi的,捞是真的想试试看这个行不行,碰碰运气,或者是面试官比较闲现在,没事捞个人看看。kpi算HR那边,但是只有你入职了,kpi才作数,面试是没有的。
双非有机会进大厂吗
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-15 17:46
暑期就挂了,秋招还有机会吗
大聪明777:研发提前批,14号刚开的,官网上面的配图上有写。提前批没过的话,秋招还可以投,不过前面的笔试/面试记录会被保留,供秋招参考
26届校招投递进展
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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