ALGORITHM/PROGRAMMERS

[프로그래머스] 자동완성 (2018 KAKAO BLIND RECRUITMENT)

0298 2021. 3. 2. 00:00

programmers.co.kr/learn/courses/30/lessons/17685

 

코딩테스트 연습 - [3차] 자동완성

자동완성 포털 다음에서 검색어 자동완성 기능을 넣고 싶은 라이언은 한 번 입력된 문자열을 학습해서 다음 입력 때 활용하고 싶어 졌다. 예를 들어, go 가 한 번 입력되었다면, 다음 사용자는 g

programmers.co.kr

2021-03-01


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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
public class Solution17685 {
    static class TrieNode {
        TrieNode[] next;
        int count = 0;
 
        TrieNode() {
            next = new TrieNode[26];
            this.count = 0;
        }
    }
 
    static class Trie {
        TrieNode root;
 
        Trie() {
            root = new TrieNode();
        }
 
        void insert(String str) {
            TrieNode node = root;
 
            for(int i = 0; i < str.length(); i++) {
                int idx = str.charAt(i) - 'a';
                if(node.next[idx] == null) node.next[idx] = new TrieNode();
                node.next[idx].count++;
                node = node.next[idx];
            }
        }
 
        int count(String str) {
            TrieNode node = root;
            int cnt = 0;
            for(int i = 0; i < str.length(); i++) {
                int idx = str.charAt(i) - 'a';
                cnt++;
                if(node.next[idx].count == 1return cnt;
                node = node.next[idx];
            }
            return cnt;
        }
    }
 
    public static int solution(String[] words) {
        int answer = 0;
        Trie t = new Trie();
        for (String word : words) {
            t.insert(word);
        }
 
        for(String word: words) {
            answer += t.count(word);
        }
        return answer;
    }
 
    public static void main(String[] args) {
        String[] w = {"go""gone""guild"};
//        String[] w = {"abc","def","ghi","jklm"};
        System.out.println(solution(w));
 
    }
}
 
cs

 

#문제풀이

Trie 자료구조를 이용해서 풀었다.

 

count함수에서 cnt++을 해주면서, 만약 node의 count 값이 1이 되면 더 이상 뒤에 글자를 몰라도 되는 것이므로 return 했다.