题解 | #字符串排序#

字符串排序

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

import java.util.*;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        int a = 'a';
        int z = 'z';
        TreeMap<String, StringBuilder> map = new TreeMap<String, StringBuilder> ();
        TreeMap<Integer, String> map2 = new TreeMap<Integer, String>();
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            String str = in.nextLine();
            for (int i = 0; i < str.length(); i++) {
                Character curChar = str.charAt(i);
                String curLow = curChar.toString().toLowerCase();
                int curCharInt = (int)curLow.charAt(0);
                if (curCharInt > a - 1 && curCharInt < z + 1) {
                    StringBuilder sb =  map.get(curLow);
                    if (sb == null) {
                        sb = new StringBuilder();
                    }
                    sb.append(curChar);
                    map.put(curLow, sb);
                } else {
                    map2.put(i, curLow);
                }
            }
            StringBuilder sbTotal =  new StringBuilder();
        
            //    Iterator<Map.Entry<String, StringBuilder>> it= map.entrySet().iterator();
            //    while(it.hasNext()){
            //     Map.Entry<String, StringBuilder> entry = it.next();
            //     entry.getValue()
            //    }
            Set<Map.Entry<String, StringBuilder>> entrySet = map.entrySet();
            for (Map.Entry<String, StringBuilder> entry : entrySet) {
                StringBuilder sb = entry.getValue();
                sbTotal.append(sb);
            }
            Set<Map.Entry<Integer, String>> entrySet2 = map2.entrySet();
            for (Map.Entry<Integer, String> entry : entrySet2) {
                Integer key = entry.getKey();
                String value = entry.getValue();
               sbTotal.insert(key,value);
            }
            System.out.println(sbTotal);
        }
    }
}

全部评论

相关推荐

03-29 19:11
门头沟学院 Java
wyp_davis:是可以这样的,不过只要交钱就是假的
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务