华为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();
        }
    }
}
相关推荐
初恋叫萱萱1 小时前
构建高性能生成式AI应用:基于Rust Axum与蓝耘DeepSeek-V3.2大模型服务的全栈开发实战
开发语言·人工智能·rust
cyforkk2 小时前
12、Java 基础硬核复习:集合框架(数据容器)的核心逻辑与面试考点
java·开发语言·面试
我材不敲代码6 小时前
Python实现打包贪吃蛇游戏
开发语言·python·游戏
身如柳絮随风扬7 小时前
Java中的CAS机制详解
java·开发语言
韩立学长9 小时前
【开题答辩实录分享】以《基于Python的大学超市仓储信息管理系统的设计与实现》为例进行选题答辩实录分享
开发语言·python
风筝在晴天搁浅9 小时前
hot100 78.子集
java·算法
froginwe119 小时前
Scala 循环
开发语言
m0_706653239 小时前
C++编译期数组操作
开发语言·c++·算法
故事和你919 小时前
sdut-Java面向对象-06 继承和多态、抽象类和接口(函数题:10-18题)
java·开发语言·算法·面向对象·基础语法·继承和多态·抽象类和接口
Bruk.Liu10 小时前
(LangChain实战2):LangChain消息(message)的使用
开发语言·langchain