题解 | #数据分类处理#

数据分类处理

https://www.nowcoder.com/practice/9a763ed59c7243bd8ab706b2da52b7fd

import java.util.*;
import java.util.regex.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            int i = in.nextInt();
            String[] I = new String[i];
            for(int n=0;n<i;n++) {
                I[n]=in.next();
            }
            int r = in.nextInt();
            Integer[] R = new Integer[i];
            HashSet<Integer> set = new HashSet<Integer>(); //使用HashSet对R的输入进行去重处理
            for(int n=0;n<r;n++) {
                set.add(in.nextInt());
            }
            R=set.toArray(new Integer[0]); //将set转为数组
            Arrays.sort(R); //对数组排序
            List<String> result = new ArrayList<String>(); //结果保存集
            for(Integer integer : R) { //遍历去重后的R
                Pattern p = Pattern.compile("("+integer+")"); //利用正则匹配
                int count = 0; //记录出现次数
                for(int n=0;n<i;n++) {
                    if(p.matcher(I[n]).find()) {
                        count++;
                        result.add(n+""); //存入下标
                        result.add(I[n]); //存入数字                        
                    }
                }
                if(count!=0) { 
                    result.add(result.size()-count*2 ,integer+""); //将出现数字插入
                    result.add(result.size()-count*2 ,count+""); //出现次数插入
                }
            }
            result.add(0, result.size()+""); //最后插入总数
            for(String s : result)
                System.out.print(s+" ");
        }
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务