이 문제는 집합의 교집합을 이용해야한다.
집합 HashSet
- addAll() 합집합
- retainAll() 교집합
- removeAll() 차집합
- containsAll() 부분집합 포함 여부
푸는 과정은,
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
public class Main{
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
StringTokenizer st = new StringTokenizer(br.readLine()," ");
int N=Integer.parseInt(st.nextToken());
int M=Integer.parseInt(st.nextToken());
Set<String> NoListen = new HashSet<>();
Set<String> NoSee = new HashSet<>();
for(int i=0; i<N; i++)
NoListen.add(br.readLine());
for(int i=0; i<M; i++)
NoSee.add(br.readLine());
NoListen.retainAll(NoSee);
ArrayList<String> list = new ArrayList<String>(NoListen);
Collections.sort(list);
for(String value : list)
sb.append(value+"\n");
System.out.println(list.size());
System.out.print(sb);
br.close();
}
}