题解 | #字符串排序#

字符串排序

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);
        while (in.hasNext()) {
            String str = in.nextLine();
            char[] stc = new char[str.length()];
            Map<Integer, Character> map = new TreeMap<>();
            int k = 0;
            for (int i = 0; i < str.length(); i++) {
                char ii = str.charAt(i);
                if ((ii >= 'a' && ii <= 'z') || (ii >= 'A' && ii <= 'Z')) {
                    stc[k] = ii;
                    k++;
                } else {
                    map.put(i, ii);
                }
            }
            for (int i = 1; i < k ; i++) {
                for (int j = i ; j > 0; j--) {
                    int cc1 = 0;
                    int cc2 = 0;
                    int b = 'z' - 'Z';
                    if (stc[j] >= 'A' && stc[j] <= 'Z') {
                        cc1 = stc[j] + b;
                    } else cc1 = stc[j];
                    if (stc[j-1] >= 'A' && stc[j-1] <= 'Z') {
                        cc2 = stc[j-1] + b;
                    } else cc2 = stc[j-1];
                    if (cc2 > cc1) {
                        char hh = stc[j-1];
                        stc[j-1] = stc[j];
                        stc[j] = hh;
                    }
                }
            }
            StringBuilder stringBuilder = new StringBuilder();
            int m = 0;
            for (int i = 0; i < str.length(); i++) {
                if (map.get(i) == null) {
                    stringBuilder.append(stc[m]);
                    m++;
                } else {
                    stringBuilder.append(map.get(i));
                }
            }
            System.out.println(stringBuilder);
        }
    }
}

全部评论

相关推荐

爱看电影的杨桃allin春招:我感觉你在炫耀
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务