반응형

문제 출처 :


https://leetcode.com/problems/add-and-search-word-data-structure-design/



알고리즘 분석 :


문제 해결에 필요한 사항

1. 트라이


Trie를 정적으로 할당하여 시간을 단축시킨다. 


word를 Trie에 넣어주고 BFS를 통하여 search를 해준다.


이때 search하고자하는 단어의 끝에 도착했고, 이때 isEnd == true라면 찾아낸 것으로 판단한다.






소스 코드 : 


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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <queue>
 
#define MAX_NODE 26
 
using namespace std;
 
struct Trie{
    Trie *next[MAX_NODE];
    bool isEnd;
};
 
struct INFO{
    Trie *cur;
    int idx;
};
Trie triePool[100002];
int trieIdx;
Trie *root;
Trie *trieAlloc(){
    for(int i = 0 ; i < MAX_NODE; i++)
        triePool[trieIdx].next[i] = nullptr;
    triePool[trieIdx].isEnd = false;
    
    return &triePool[trieIdx++];
}
 
class WordDictionary {
public:
    /** Initialize your data structure here. */
    WordDictionary() {
        trieIdx = 0;
        root = trieAlloc();
    }
    
    /** Adds a word into the data structure. */
    void addWord(string word) {
        Trie *cur = root;
        int len = word.size();
        for(int i = 0 ; i < len; i ++){
            char ch = word[i] - 'a';
            
            if(!cur->next[ch])
                cur->next[ch] = trieAlloc();
            
            cur = cur->next[ch];
        }
        cur->isEnd = true;
    }
    
    /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
    bool search(string word) {
        int len = word.size();
        
        queue<INFO> q;
        
        q.push({root, 0});
        
        while(!q.empty()){
            Trie *cur = q.front().cur;
            int idx = q.front().idx;
            char ch = word[idx];
            
            if(idx == len && cur->isEnd)
                return true;
                
            if(ch != '.'
                ch -= 'a';
            
            q.pop();
            
            for(int i = 0 ; i < MAX_NODE; i++) {
                if(ch == '.' && cur->next[i]) 
                    q.push({cur->next[i], idx + 1});
                else if(cur->next[i] && i == ch)
                    q.push({cur->next[i], idx + 1});
            }
        }
        
        return false;
    }
};
 
/**
 * Your WordDictionary object will be instantiated and called as such:
 * WordDictionary* obj = new WordDictionary();
 * obj->addWord(word);
 * bool param_2 = obj->search(word);
 */
cs


반응형

'Applied > 알고리즘 문제풀이' 카테고리의 다른 글

[3번] Longest Substring Without Repeating Characters  (0) 2019.05.23
[2번] Add Two Numbers  (0) 2019.05.01
[1260번] 화학물질2  (0) 2019.04.27
[1257번] K번째 문자열  (0) 2019.04.21
[17136번] 색종이 붙이기  (0) 2019.04.11