Set을 이용
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.BufferedReader; | |
import java.io.InputStreamReader; | |
import java.util.ArrayList; | |
import java.util.Collections; | |
import java.util.HashSet; | |
import java.util.List; | |
import java.util.Set; | |
import java.util.StringTokenizer; | |
public class Main { | |
public static void main(String[] args) throws Exception { | |
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); | |
StringTokenizer st = new StringTokenizer(br.readLine()); | |
int n = Integer.parseInt(st.nextToken()); | |
int m = Integer.parseInt(st.nextToken()); | |
Set<String> set = new HashSet<>(); | |
List<String> list = new ArrayList<>(); | |
while (n-- > 0) { | |
String name = br.readLine(); | |
set.add(name); | |
} | |
while (m-- > 0) { | |
String name = br.readLine(); | |
if (set.contains(name)) { | |
list.add(name); | |
} | |
} | |
Collections.sort(list); | |
StringBuilder ans = new StringBuilder(); | |
ans.append(list.size()).append('\n'); | |
for (String str : list) { | |
ans.append(str).append('\n'); | |
} | |
System.out.print(ans); | |
br.close(); | |
} | |
} |
ArrayList를 이용
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.BufferedReader; | |
import java.io.InputStreamReader; | |
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.Collections; | |
import java.util.StringTokenizer; | |
public class Main { | |
public static void main(String[] args)throws Exception { | |
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); | |
StringTokenizer st; | |
st=new StringTokenizer(br.readLine()); | |
int N=Integer.parseInt(st.nextToken()); | |
int M=Integer.parseInt(st.nextToken()); | |
ArrayList<String>a1=new ArrayList<>(); | |
for(int i=0;i<N;i++){ | |
a1.add(br.readLine()); | |
} | |
Collections.sort(a1); | |
String[]temp=new String[a1.size()]; | |
temp=a1.toArray(temp); | |
ArrayList<String>a2=new ArrayList<>(); | |
for(int i=0;i<M;i++){ | |
String s=br.readLine(); | |
int idx=Arrays.binarySearch(temp, s); | |
if(idx>=0){ | |
a2.add(s); | |
} | |
} | |
Collections.sort(a2); | |
System.out.println(a2.size()); | |
for(String s : a2){ | |
System.out.println(s); | |
} | |
} | |
} |
'백준 알고리즘 > JAVA' 카테고리의 다른 글
백준 4673번 셀프 넘버 (0) | 2019.01.21 |
---|---|
자바 백준 5585번 거스름돈 (0) | 2018.09.02 |
자바 백준 7568번 덩치 (1) | 2018.08.25 |
자바 백준 1065번 한수 (0) | 2018.08.23 |
자바 백준 2231번 분해합 (0) | 2018.08.23 |