题解 | #字符串排序#

字符串排序

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

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        String str = in.nextLine();
        char[] charArr = new char[str.length()];
        // 纯字母
        ArrayList<Character> list = new ArrayList<>();
        // 初始化
        for (int i = 0; i < str.length(); i++) {
            char t = str.charAt(i);
            if ((t >= 'a' && t <= 'z') || (t >= 'A' && t <= 'Z')) {
                list.add(t);
            } else {
                charArr[i] = t;
            }
        }
        // 排序子母
        Collections.sort(list, new Comparator<Character>() {
            @Override
            public int compare(Character o1, Character o2) {
                Character t1 = Character.toLowerCase(o1);
                Character t2 = Character.toLowerCase(o2);
                return t1.compareTo(t2);
            }
        });
        int index = 0;
        for (int i = 0; i < str.length(); i++) {
            if ((int)charArr[i] != 0) {
                System.out.print(charArr[i]);
            } else {
                System.out.print(list.get(index));
                index++;
            }
        }
    }
}

全部评论

相关推荐

废铁汽车人:秋招真是牛鬼蛇神齐聚一堂
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务