题解 | #字符串排序#

字符串排序

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

利用List集合的sort方法,插入排序,可保证大小相同的情况下,顺序是原来的顺序。

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 str = in.nextLine();
            HashMap<Integer, String> hm = new HashMap<>();
            ArrayList<Character> list = new ArrayList<>();
            for(int i=0; i<str.length(); i++){
                String s = str.charAt(i) + "";
                if(s.matches("[^a-zA-Z]")){
                    hm.put(i, s);
                }else{
                    list.add(str.charAt(i));
                }
            }
            // 插入排序,如果两个值相同,那么后面的会排在后面。不会影响原来的排序
            list.sort((o1,o2) ->{
                return (o1+"").toUpperCase().charAt(0) - (o2+"").toUpperCase().charAt(0);
            });
            StringBuffer result = new StringBuffer();
            int listIndex = 0;
            for(int i=0;i<list.size()+hm.size();i++){
                if(hm.keySet().contains(i)){
                    result.append(hm.get(i));
                }else{
                    result.append(list.get(listIndex));
                    listIndex++;
                }
            }
            System.out.println(result);
        }
    }
}

全部评论

相关推荐

09-03 17:49
已编辑
四川大学 供应链管理
迷茫的大四🐶:提前实习有些坑的,卡毕业后薪资以及能力不达预期提前违约这种
我的OC时间线
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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