华为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();
        }
    }
}
相关推荐
炸膛坦客14 分钟前
单片机/C/C++八股:(十九)栈和堆的区别?
c语言·开发语言·c++
零雲16 分钟前
java面试:了解抽象类与接口么?讲一讲它们的区别
java·开发语言·面试
Jay_Franklin33 分钟前
Quarto与Python集成使用
开发语言·python·markdown
2401_831824961 小时前
代码性能剖析工具
开发语言·c++·算法
是wzoi的一名用户啊~1 小时前
【C++小游戏】2048
开发语言·c++
Sunshine for you2 小时前
C++中的职责链模式实战
开发语言·c++·算法
@我漫长的孤独流浪2 小时前
Python编程核心知识点速览
开发语言·数据库·python
qq_416018722 小时前
C++中的状态模式
开发语言·c++·算法
2401_884563242 小时前
模板代码生成工具
开发语言·c++·算法
code 小楊2 小时前
yrb 1.5.0 正式发布:Python 极简国内下载加速与全景可视化终端体验!
开发语言·python