华为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();
        }
    }
}
相关推荐
golitter.3 分钟前
python中的 @dataclass
开发语言·python
一枚小小程序员哈13 分钟前
基于springboot的零食商城的设计与实现/零食销售系统的设计与实现
java·spring boot·spring·tomcat·maven
LiuYiCheng12345615 分钟前
WebCrawler库:从网页抓取到智能处理的Python利器
开发语言·python
qqxhb16 分钟前
零基础数据结构与算法——第六章:算法设计范式与高级主题-设计技巧(上)
java·数据结构·算法·分解·空间换时间·时空平衡
野生技术架构师32 分钟前
系统改造:一次系统领域拆分的实战复盘
java·大数据·开发语言
南玖yy36 分钟前
C++多态:面向对象编程的灵魂之
运维·开发语言·数据库·c++·后端·c·c语音
一碗绿豆汤38 分钟前
JAVA+AI教程-第四天
java·开发语言·人工智能
YuTaoShao39 分钟前
【LeetCode 热题 100】34. 在排序数组中查找元素的第一个和最后一个位置——二分查找
java·数据结构·算法·leetcode
典孝赢麻崩乐急40 分钟前
Java学习-----如何创建线程
java·学习
一车小面包41 分钟前
Python包和模块Day8
开发语言·python