CS/알고리즘_KAKAO BLIND RECRUITMENT

2020 KAKAO BLIND RECRUITMENT : 가사 검색

Jedy_Kim 2021. 10. 18. 17:13
728x90

https://programmers.co.kr/learn/courses/30/lessons/60060

 

코딩테스트 연습 - 가사 검색

 

programmers.co.kr

// 코드

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
64
65
66
67
68
69
70
class Solution {
    
    class Trie {
        
        Trie[] child = new Trie[26];
        int count;
        int aLetter = Character.getNumericValue('a'); // 'a' 에 대한 아스키 코드
        
        void insert(String str) {
            Trie curr = this;
            for(char ch : str.toCharArray()) {
                curr.count++;
                int idx = Character.getNumericValue(ch) - aLetter;
                if(curr.child[idx] == null) curr.child[idx] = new Trie();
                
                curr = curr.child[idx];
            }
            curr.count++;
        }
        
        int search(String str) {
            Trie curr = this;
            for(char ch : str.toCharArray()) {
                if(ch == '?'return curr.count;
                curr = curr.child[Character.getNumericValue(ch) - aLetter];
                if(curr == nullreturn 0;
            }
            return curr.count;
        }
        
    }
    
    Trie[] TrieRoot   = new Trie[10000];
    Trie[] ReTrieRoot = new Trie[10000];
    
    public int[] solution(String[] words, String[] queries) {
        int[] answer = new int[queries.length];
        int ansIdx = 0;
        
        for(String str : words) {
            int idx = str.length() - 1;
            if(TrieRoot[idx] == null) {
                TrieRoot[idx]   = new Trie();
                ReTrieRoot[idx] = new Trie();
            }
            
            TrieRoot[idx].insert(str);
            str = new StringBuilder(str).reverse().toString();
            ReTrieRoot[idx].insert(str);
        }
        
        for(String str : queries) {
            int idx = str.length() - 1;
            if(TrieRoot[idx] == null) {
                answer[ansIdx++= 0;
                continue;
            }
            
            if(str.charAt(0!= '?') {
                answer[ansIdx++= TrieRoot[idx].search(str);
            } else {
                str = new StringBuilder(str).reverse().toString();
                answer[ansIdx++= ReTrieRoot[idx].search(str);
            }
            
        }
        
        return answer;
    }
}
cs

 

반응형