小米校园招聘笔试题寻找相似的帖子

来源:互联网 发布:淘宝网禅服 编辑:程序博客网 时间:2024/04/27 19:06

寻找标题相同或者关键字一样的帖子,按组输出帖子的id,我们可以先用两个for循环将所有相似的帖子放到二维数组里面,arr[][],例如arr[i][j]表示id是i的帖子和j的帖子相似,然后就开始遍历这二维数组按照要求输出id组

首先建表示帖子的类Post

public class Post {public int mid;public String mtitle;public List<String> mkeys;}
然后Message类用来处理题目

public class Message {public static void main(String[] args){int i,j;int N=5;Post[] post=new Post[N];post[0]=new Post();post[0].mid=0;post[0].mtitle="i have a dream";post[0].mkeys=new ArrayList<String>();post[0].mkeys.add("dream");post[0].mkeys.add("help");//post[0].mkeys.add("help");post[1]=new Post();post[1].mid=1;post[1].mtitle="i have a dream";post[1].mkeys=new ArrayList<String>();post[1].mkeys.add("somee");post[1].mkeys.add("much");post[1].mkeys.add("goo");post[2]=new Post();post[2].mid=2;post[2].mtitle="so luck";post[2].mkeys=new ArrayList<String>();post[2].mkeys.add("somee");post[2].mkeys.add("hello");post[2].mkeys.add("go");post[3]=new Post();post[3].mid=3;post[3].mtitle="my so luck";post[3].mkeys=new ArrayList<String>();post[3].mkeys.add("work");post[3].mkeys.add("thank");post[3].mkeys.add("sorry");post[4]=new Post();post[4].mid=4;post[4].mtitle="work hard";post[4].mkeys=new ArrayList<String>();post[4].mkeys.add("work");post[4].mkeys.add("ccnu");post[4].mkeys.add("dy");int arr[][]=new int[N+1][N+1];arr[0][0]=0;for(i=0;i<=N;i++){arr[0][i]=0;arr[i][0]=0;if(i!=0)arr[i][i]=0;}for(i=1;i<=N;i++){for(j=i+1;j<=N;j++){if(post[i-1].mtitle.equalsIgnoreCase(post[j-1].mtitle)||findsameword(post[i-1].mkeys,post[j-1].mkeys)){arr[i][j]=1;arr[j][i]=1;}else{arr[i][j]=0;arr[j][i]=0;}}}int[] index=new int[N];for(i=0;i<N;i++)index[i]=0;for(i=0;i<N;i++){boolean f=false;if(index[i]==0){f=true;System.out.print(post[i].mid+"  ");index[i]=1;findid(post,post[i].mid+1,index,arr,N);}if(f)System.out.println();}}static void findid(Post[] post, int i,int[] index,int[][] arr,int N){int j;for(j=i+1;j<=N;j++){if(index[j-1]==0&&arr[i][j]==1){System.out.print(post[j-1].mid+"  ");index[j-1]=1;findid(post,j,index,arr,N);}}}static boolean findsameword(List<String> key1,List<String> key2){boolean f=false;int len1=key1.size(),len2=key2.size();int i,j;for(i=0;i<len1;i++){for(j=0;j<len2;j++){if(key1.get(i).equalsIgnoreCase(key2.get(j))){f=true;break;}}if(f)break;}return f;}}

0 0