字节跳动
字节3.15笔试第一题,百思不得其解的bug,终于做出来了
import java.util.*; import java.util.Map.Entry; public class Main { public static void main(String[] args) { Scanner sc =new Scanner(System.in); int n = sc.nextInt(); String cup = sc.nextLine(); Map<String,List<String>> map = new HashMap<>(); List<String> ls = new ArrayList<>(); int change = 0; for(int i=0;i<n;i++){ String temp = sc.nextLine(); ls.add(temp); } for(int i = 0;i<n;i++){ change=0; String temp[]=ls.get(i).split(" "); Iterator<Entry<String, List<String>>> it = map.entrySet().iterator(); while(it.hasNext()){ Map.Entry entry = (Entry) it.next(); String key = (String) entry.getKey(); List<String> list= (List)entry.getValue(); if(temp[1].equals(key)){ list.add(temp[0]); map.put(key, list); change = 1; } } if (change==0){ List<String> tlist = new ArrayList<>(); tlist.add(temp[0]); map.put(temp[1],tlist); } } Iterator it = map.entrySet().iterator(); while(it.hasNext()){ Map.Entry entry = (Entry) it.next(); String key = (String) entry.getKey(); List<String> list= (List)entry.getValue(); System.out.print(key); System.out.print(" "); Collections.sort(list); for(int i=0;i<list.size();i++){ System.out.print(list.get(i)); System.out.print(" "); } System.out.println(); } } /** 3 ads a asd a sdf a */ }