- 풀이
개미굴의 각 층을 표현하고 같은 층의 경우 사전순으로 먼저 출력되야 합니다.
TreeMap의 장점 중 하나는 자동으로 key값에 의해 자동 정렬 된다는 것입니다. (우선순위 큐와 비슷한 느낌)
저 같은 경우 Node라는 class를 만들어 현재 string과 자식 Treemap을 생성해 주었다.
맨 처음 연결시킬 string 입력이 올 시 now라는 Node를 만들어 준 뒤 root의 위치를 할당합니다. 그 후 입력된 String이 자식 Treemap의 키값 중 해당 String으로 된 TreeMap이 없다면 새롭게 자식 TreeMap을 만들어 연결 시켜줍니다. 그 후, now를 자식 node를 가리키게 합니다. (해당 동작은 자식 노드를 게속 연결시켜주기 위함.)
연결이 모두 다 되었다면, root에 연결된 자식 TreeMap을 하나씩 꺼내서 자식을 타고가면서 출력해주면 됩니다.
저는 재귀 형식으로 구현했습니다.
- 코드
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
public class Main {
static StringBuilder sb;
public static void main(String[] args) throws Exception {
SetData();
System.out.println(sb);
}
// 데이터
private static void SetData() throws Exception {
InputReader in = new InputReader(System.in);
int n = in.nextInt();
Trie trie = new Trie("");
Trie node;
sb = new StringBuilder();
while(n-- > 0) {
String[] temp = in.nextLine().split(" ");
int k = Integer.parseInt(temp[0]);
node = trie;
for(int j = 0 ; j < k ; j++) {
String name = temp[j+1];
if(!node.list.containsKey(name))
node.list.put(name, new Trie(name));
node = node.list.get(name);
}
}
print(trie, -1);
}
public static void print(Trie trie, int depth) {
if(depth != -1) {
for(int i = 0; i < depth; i++) {
sb.append("--");
}
sb.append(trie.name).append("\n");
}
for(Trie tree : trie.list.values()) {
print(tree, depth+1);
}
}
}
class Trie{
TreeMap<String, Trie> list;
String name;
Trie(String name) {
list = new TreeMap<>();
this.name = name;
}
}
class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
'algorithm' 카테고리의 다른 글
[BOJ/JAVA] 백준 9177번 : 단어 섞기 (0) | 2021.09.08 |
---|---|
[BOJ/JAVA] 백준 2866번 : 문자열 잘라내기 (0) | 2021.09.08 |
[JAVA] 백준 12015번 : 가장 긴 증가하는 부분 수열 2 (0) | 2021.08.31 |
[BOJ/JAVA] 백준 2617번 : 구슬 찾기 (0) | 2021.08.27 |
[BOJ/JAVA] 백준 10800번 : 컬러볼 (0) | 2021.08.26 |