Skip to content

Commit ee6dfcc

Browse files
committed
[baekjoon] 2179번 - 비슷한 단어
1 parent 6100620 commit ee6dfcc

File tree

2 files changed

+83
-0
lines changed

2 files changed

+83
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@
5656
- 2024년 9월 11일 : [b14501](https://www.acmicpc.net/problem/14501)
5757
- 2024년 9월 12일 : [b14502](https://www.acmicpc.net/problem/14502)
5858
- 2024년 9월 13일 : [b9663](https://www.acmicpc.net/problem/9663)
59+
- 2024년 11월 28일 : [b2179](https://www.acmicpc.net/problem/2179)
5960

6061
### 해시 (Hash)
6162
- 2024년 9월 16일 : [p42576](https://school.programmers.co.kr/learn/courses/30/lessons/42576)

b2179/Main.java

+82
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
package b2179;
2+
3+
import java.io.*;
4+
import java.util.*;
5+
6+
public class Main {
7+
public static void main(String[] args) throws IOException {
8+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
9+
10+
int n = Integer.parseInt(br.readLine());
11+
List<Word> words = readWords(br, n);
12+
13+
List<Word> result = findSimilarWords(words);
14+
15+
printResult(result);
16+
}
17+
18+
private static List<Word> readWords(BufferedReader br, int n) throws IOException {
19+
List<Word> words = new ArrayList<>();
20+
21+
for (int i = 0; i < n; i++) {
22+
words.add(new Word(i, br.readLine()));
23+
}
24+
25+
return words;
26+
}
27+
28+
private static List<Word> findSimilarWords(List<Word> words) {
29+
int maxPrefixLength = 0;
30+
31+
Word first = new Word(Integer.MAX_VALUE, "");
32+
Word second = new Word(Integer.MAX_VALUE, "");
33+
34+
for (int i = 0; i < words.size(); i++) {
35+
for (int j = i + 1; j < words.size(); j++) {
36+
Word w1 = words.get(i);
37+
Word w2 = words.get(j);
38+
39+
int prefixLength = getPrefixLength(w1.value, w2.value);
40+
41+
if (prefixLength > maxPrefixLength) {
42+
maxPrefixLength = prefixLength;
43+
first = w1;
44+
second = w2;
45+
}
46+
if (prefixLength == maxPrefixLength) {
47+
if (w1.index < first.index ||
48+
(w1.index == first.index && w2.index < second.index)) {
49+
first = w1;
50+
second = w2;
51+
}
52+
}
53+
}
54+
}
55+
return Arrays.asList(first, second);
56+
}
57+
58+
private static int getPrefixLength(String s1, String s2) {
59+
int length = 0;
60+
61+
while (length < s1.length() && length < s2.length() && s1.charAt(length) == s2.charAt(length)) {
62+
length++;
63+
}
64+
65+
return length;
66+
}
67+
68+
private static void printResult(List<Word> result) {
69+
System.out.println(result.get(0).value);
70+
System.out.println(result.get(1).value);
71+
}
72+
73+
static class Word {
74+
int index;
75+
String value;
76+
77+
Word(int index, String value) {
78+
this.index = index;
79+
this.value = value;
80+
}
81+
}
82+
}

0 commit comments

Comments
 (0)