题解 | #数据分类处理#
数据分类处理
https://www.nowcoder.com/practice/9a763ed59c7243bd8ab706b2da52b7fd
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while(sc.hasNextInt()){ int m = sc.nextInt();//sum of numbers String[] nums = new String[m]; for(int i=0;i<m;i++){ nums[i] = sc.next(); } int n = sc.nextInt(); TreeSet<Integer> tree = new TreeSet<>();//get sorted arrays for(int j=0;j<n;j++){ tree.add(sc.nextInt()); } int k = 0;//number of following integers int numOfI = tree.size(); String[] ans = new String[tree.size()]; int countSum = 0; for(Integer o:tree){ String s = String.valueOf(o); StringBuilder sb = new StringBuilder(); int count=0; for(int i=0;i<m;i++){ if(nums[i].contains(s)){ sb.append(i+" "+nums[i]+" "); count++; } } countSum += count; if(count!=0){ String ansSeq = addFront(addFront(sb.toString(),String.valueOf(count)),s); ans[k]=ansSeq; k++; } else{ continue; } } StringBuilder out = new StringBuilder(); int t = 0; for(int i=0;i<numOfI;i++){ if(ans[i]!=null){ out.append(ans[i]); t++; } } int allSum = countSum*2+t*2; System.out.println(allSum+" "+out.toString()); } } public static String addFront(String stb,String s){ String sb = new String(); sb = s+" "+stb; return sb; } } for(int i=0;i<m;i++){ nums[i] = sc.next(); } int n = sc.nextInt(); TreeSet<Integer> tree = new TreeSet<>();//get sorted arrays for(int j=0;j<n;j++){ tree.add(sc.nextInt()); } int k = 0;//number of following integers int numOfI = tree.size(); String[] ans = new String[tree.size()]; int countSum = 0; for(Integer o:tree){ String s = String.valueOf(o); StringBuilder sb = new StringBuilder(); int count=0; for(int i=0;i<m;i++){ if(nums[i].contains(s)){ sb.append(i+" "+nums[i]+" "); count++; } } countSum += count; if(count!=0){ String ansSeq = addFront(addFront(sb.toString(),String.valueOf(count)),s); ans[k]=ansSeq; k++; } else{ continue; } } StringBuilder out = new StringBuilder(); int t = 0; for(int i=0;i<numOfI;i++){ if(ans[i]!=null){ out.append(ans[i]); t++; } } int allSum = countSum*2+t*2; System.out.println(allSum+" "+out.toString()); } } public static String addFront(String stb,String s){ String sb = new String(); sb = s+" "+stb; return sb; }
最后输出的字符串是“总的参数个数 第一个匹配 第一个匹配到的数 匹配到的数的索引 匹配到的数......”
总的参数个数 是 有匹配结果的数*2(匹配以及匹配的参数)+所有匹配结果的个数*2(索引和数本身)
流程是
1.利用TreeSet去重排序所有要匹配的数
2.开始遍历,匹配第一行的数据,直接将结果组成String再加入到一个字符串组中(保持有序),注意假如一个匹配结果都没有
那么就忽略这个要匹配的数
3.最后将总的参数个数算出来,加到字符串的最前面
由于经常使用字符串前加字符的操作,写了一个简单的函数addFront()