题解 | 字符串排序

字符串排序

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);
        String str = in.nextLine();
        char[] ch = str.toCharArray();
        String letter = "";  //专门存放字母
        List<Integer> index = new ArrayList<>();  //存放其他字符的位置下标
        for (int i = 0; i < str.length(); i++) {
            if (!Character.isLetter(ch[i])) {
                index.add(i);
            } else {
                letter += ch[i];
            }
        }

        char[] l = letter.toCharArray();
        for (int i = 0; i < letter.length() - 1; i++) {
            for (int j = 0; j < letter.length() - i - 1; j++) {
                char front = Character.toLowerCase(l[j]);
                char rear = Character.toLowerCase(l[j+1]);
                if (front > rear) {
                    char a = l[j];
                    l[j] = l[j + 1];
                    l[j + 1] = a;
                }
            }
        }

        //输出
        for (int i = 0, j = 0,k = 0; k < str.length(); k++) {
            if (j < index.size() && k == index.get(j)) {
                System.out.print(ch[k]);
                j++;
            } else {
                System.out.print(l[i++]);
            }
        }
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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