华为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();
        }
    }
}
相关推荐
传奇开心果编程5 分钟前
【Rust入门知识点学与练】第4课:条件判断 if / else
开发语言·学习·rust
m0_3807438724 分钟前
给 Claude API 调用补上超时重试和错误分类
开发语言·人工智能·php
天远数科25 分钟前
风险治理实战:基于天远车信盟出险构建自动化理赔核保流水线
java·网络·人工智能·自动化
Draw Stars33 分钟前
Git BASH安装教程
开发语言·git·bash
vortex541 分钟前
一文讲透 Zsh 与 Bash 的区别
开发语言·bash
千谦阙听1 小时前
C++类和对象(中):默认成员函数、构造与析构、拷贝构造、运算符重载
开发语言·c++·学习
骇客野人1 小时前
SpringBoot电商系统用户注册、登录、留存及数据埋点设计与落地实施方案
java·spring boot·后端
qiuhaipeng11 小时前
Claude code 升级后上下文长度变短问题
java·前端·数据库
wxwx_bscxy3222 小时前
基于Python新冠疫情可视化分析系统的设计与实现
java·数据库·spring boot·python·微信小程序·sqlite
evans在进步3 小时前
Tomcat NIO 工作原理详解:从 Acceptor、Poller 到容器处理链
java·tomcat·nio