华为OD机考-分班问题/幼儿园分班-字符串(JAVA 2025B卷)



java 复制代码
import java.util.*;
public class FenBan {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNextLine()){
            String[] split = sc.nextLine().split("\\s+");
            solve(split);
        }
    }

    private static void solve(String[] split){
        int[] names = new int[split.length];
        String[] tags = new String[split.length];
        for(int i =0;i< split.length;i++){
            String[] split1 = split[i].split("/");
            names[i] = Integer.parseInt(split1[0]);
            tags[i] = split1[1];
        }
        List<List<Integer>> list = new ArrayList<>();
        for (int i=1;i<split.length;i++) {
            if(tags[i].equals("Y")){//names[i-1]和names[i]是同一个班的学生
                if(list.isEmpty()){//首次为空,直接加
                    List<Integer> innerList = new ArrayList<>();
                    innerList.add(names[i-1]);
                    innerList.add(names[i]);
                    list.add(innerList);
                }else{
                    boolean flag = false;
                    for(List<Integer> innerList:list){//当前学生和前一个学生是否在同一个班,若是则沿用list
                        if(innerList.contains(names[i-1])){
                            innerList.add(names[i]);//加入当前班的学生名称
                            flag = true;
                        }
                    }
                    if(!flag){//若不在同一个班,新开一个list
                        List<Integer> innerList = new ArrayList<>();
                        innerList.add(names[i-1]);
                        innerList.add(names[i]);
                        list.add(innerList);
                    }
                }
            }
        }
        //排序
        for(List<Integer> innerList:list){
            innerList.sort((o1, o2) -> o1-o2);
        }
        //打印
        for(List<Integer> innerList:list){
            for(int i=0;i<innerList.size();i++){
                System.out.print(innerList.get(i));
                if(i!=innerList.size()-1){
                    System.out.print(" ");
                }
            }
            System.out.println();
        }
    }
}
相关推荐
皮皮林5518 小时前
Java性能调优黑科技!1行代码实现毫秒级耗时追踪,效率飙升300%!
java
冰_河8 小时前
QPS从300到3100:我靠一行代码让接口性能暴涨10倍,系统性能原地起飞!!
java·后端·性能优化
桦说编程11 小时前
从 ForkJoinPool 的 Compensate 看并发框架的线程补偿思想
java·后端·源码阅读
躺平大鹅12 小时前
Java面向对象入门(类与对象,新手秒懂)
java
初次攀爬者13 小时前
RocketMQ在Spring Boot上的基础使用
java·spring boot·rocketmq
花花无缺13 小时前
搞懂@Autowired 与@Resuorce
java·spring boot·后端
Derek_Smart15 小时前
从一次 OOM 事故说起:打造生产级的 JVM 健康检查组件
java·jvm·spring boot
NE_STOP16 小时前
MyBatis-mybatis入门与增删改查
java
孟陬19 小时前
国外技术周刊 #1:Paul Graham 重新分享最受欢迎的文章《创作者的品味》、本周被划线最多 YouTube《如何在 19 分钟内学会 AI》、为何我不
java·前端·后端