Skip to content

Commit ffd2fab

Browse files
authored
Merge pull request #781 from AlgorithmWithGod/0224LJH
[20250831] BOJ / G5 / 비슷한 단어 / 이종환
2 parents 10da0ec + 84df85c commit ffd2fab

File tree

1 file changed

+91
-0
lines changed

1 file changed

+91
-0
lines changed
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
```java
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class Main {
6+
7+
static int size,ansIdx, longest=0;
8+
static String ans1,ans2;
9+
static String[] words;
10+
11+
static class TrieNode{
12+
Map<Character, TrieNode> children = new HashMap<>();
13+
String word;
14+
int num;
15+
boolean isWord;
16+
17+
public TrieNode(String word, int num){
18+
this.word = word;
19+
this.num = num;
20+
}
21+
}
22+
23+
static void insert(String nWord, int wordNum){
24+
TrieNode node = root;
25+
int len = 0;
26+
int tempIdx = 0;
27+
boolean isEnd = false;
28+
String tempWord = "";
29+
30+
for (int i = 0; i < nWord.length(); i++){
31+
Character c = nWord.charAt(i);
32+
if (node.children.containsKey(c)){
33+
node = node.children.get(c);
34+
if (!isEnd){
35+
len++;
36+
tempWord = node.word;
37+
tempIdx = node.num;
38+
}
39+
} else {
40+
node.children.put(c, new TrieNode(nWord,wordNum));
41+
node = node.children.get(c);
42+
isEnd = true;
43+
}
44+
}
45+
46+
if (longest < len || (longest == len && tempIdx < ansIdx )){
47+
ansIdx = tempIdx;
48+
longest = len;
49+
ans1 = tempWord;
50+
ans2 = nWord;
51+
}
52+
}
53+
54+
static TrieNode root = new TrieNode("",-1);
55+
56+
public static void main(String[] args) throws Exception {
57+
init();
58+
process();
59+
print();
60+
61+
}
62+
63+
public static void init() throws IOException {
64+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
65+
size =Integer.parseInt(br.readLine());
66+
words = new String[size];
67+
ansIdx = -1;
68+
for (int i = 0; i < size; i++) {
69+
words[i] = br.readLine();
70+
71+
}
72+
}
73+
74+
public static void process(){
75+
for(int i = 0; i < size; i++){
76+
insert(words[i],i);
77+
// System.out.println("longest = " + longest);
78+
// System.out.println("ans1 = " + ans1);
79+
// System.out.println("ans2 = " + ans2);
80+
}
81+
}
82+
83+
public static void print(){
84+
System.out.println(longest);
85+
System.out.println(ans1);
86+
System.out.println(ans2);
87+
}
88+
89+
90+
}
91+
```

0 commit comments

Comments
 (0)