Post

๐Ÿงฉ Baekjoon 1181 - ๋‹จ์–ด ์ •๋ ฌ

๐Ÿงฉ Baekjoon 1181 - ๋‹จ์–ด ์ •๋ ฌ

๋ฌธ์ œ

์•ŒํŒŒ๋ฒณ ์†Œ๋ฌธ์ž๋กœ ์ด๋ฃจ์–ด์ง„ N๊ฐœ์˜ ๋‹จ์–ด๊ฐ€ ๋“ค์–ด์˜ค๋ฉด ์•„๋ž˜์™€ ๊ฐ™์€ ์กฐ๊ฑด์— ๋”ฐ๋ผ ์ •๋ ฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

  1. ๊ธธ์ด๊ฐ€ ์งง์€ ๊ฒƒ๋ถ€ํ„ฐ
  2. ๊ธธ์ด๊ฐ€ ๊ฐ™์œผ๋ฉด ์‚ฌ์ „ ์ˆœ์œผ๋กœ

๋‹จ, ์ค‘๋ณต๋œ ๋‹จ์–ด๋Š” ํ•˜๋‚˜๋งŒ ๋‚จ๊ธฐ๊ณ  ์ œ๊ฑฐํ•ด์•ผ ํ•œ๋‹ค.

์ž…๋ ฅ

์ฒซ์งธ ์ค„์— ๋‹จ์–ด์˜ ๊ฐœ์ˆ˜ N์ด ์ฃผ์–ด์ง„๋‹ค. (1 โ‰ค N โ‰ค 20,000) ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ N๊ฐœ์˜ ์ค„์— ๊ฑธ์ณ ์•ŒํŒŒ๋ฒณ ์†Œ๋ฌธ์ž๋กœ ์ด๋ฃจ์–ด์ง„ ๋‹จ์–ด๊ฐ€ ํ•œ ์ค„์— ํ•˜๋‚˜์”ฉ ์ฃผ์–ด์ง„๋‹ค. ์ฃผ์–ด์ง€๋Š” ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๋Š” 50์„ ๋„˜์ง€ ์•Š๋Š”๋‹ค.

์ถœ๋ ฅ

์กฐ๊ฑด์— ๋”ฐ๋ผ ์ •๋ ฌํ•˜์—ฌ ๋‹จ์–ด๋“ค์„ ์ถœ๋ ฅํ•œ๋‹ค.

์˜ˆ์ œ

โœ… ์ž…๋ ฅ 1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
13
but
i
wont
hesitate
no
more
no
more
it
cannot
wait
im
yours

โœ… ์ถœ๋ ฅ 1

1
2
3
4
5
6
7
8
9
10
11
i
im
it
no
but
more
wait
wont
yours
cannot
hesitate

์ž‘์„ฑ ์ฝ”๋“œ

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.io.BufferedReader;  
import java.io.IOException;  
import java.io.InputStreamReader;  
import java.util.Arrays;  
import java.util.Comparator;  
  
public class Main {  
	public static void main(String[] args) throws IOException {  
		// 1. ๋ณ€์ˆ˜ ์„ ์–ธ ๋ฐ ์ดˆ๊ธฐํ™”  
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));  
		int n = Integer.parseInt(br.readLine());  
		String[] words = new String[n];  
		
		// 2. ๋‹จ์–ด ๋ชฉ๋ก ์ดˆ๊ธฐํ™”  
		for (int i = 0; i < n; i++) words[i] = br.readLine();  
		
		// 3. ์ŠคํŠธ๋ฆผ ์ฒ˜๋ฆฌ  
		words = Arrays.stream(words)  
			.sorted(  
				Comparator.comparingInt(String::length)         // ๊ธธ์ด์ˆœ ์ •๋ ฌ  
					.thenComparing(Comparator.naturalOrder())   // ์‚ฌ์ „์ˆœ ์ •๋ ฌ  
			)  
			.distinct()                                         // ์ค‘๋ณต ์ œ๊ฑฐ  
			.toArray(String[]::new);  
			
		// 4. ์ถœ๋ ฅ  
		for (String word : words) System.out.println(word);  
	}  
}
  • Stream์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š”๋‹ค๋ฉด ์–ด๋–ป๊ฒŒ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ์„์ง€ ์ƒ๊ฐํ•ด๋ณด์•„์•ผ๊ฒ ๋‹ค.
This post is licensed under CC BY 4.0 by the author.