관리 메뉴

Mini

리트코드 208. Trie 구현 c++ // 트라이복습, c클래스 초기화 방법 본문

Algorithm/트라이

리트코드 208. Trie 구현 c++ // 트라이복습, c클래스 초기화 방법

Mini_96 2024. 5. 18. 20:42

https://leetcode.com/problems/implement-trie-prefix-tree/

 

1. c클래스 초기화 방법

private: int a, int arr[30]

public : className() : a(0), arr() {}

암기할것

 

2. 트라이 복습

1. 자식배열을 가진다. Trie* child[26]

2. 새로운 자식할당은 new Trie로 한다.

자식할당시 cur->child[c-'a'] = new Trie() 

암기할것

 

class Trie {
private:
    int isEnd;
    Trie* child[26];
public:
    Trie() : child(),isEnd(0) {} //초기화방법 암기할것
    
    void insert(string word) {
        Trie* cur=this;
        for(auto c : word){
            if(cur->child[c-'a']==nullptr){
                cur->child[c-'a']=new Trie(); //자식할당!
            }
            cur=cur->child[c-'a'];
        }
        cur->isEnd=1;
    }
    
    bool search(string word) {
        Trie* cur=this;
        for(auto c : word){
            if(cur->child[c-'a']==nullptr){
                return false;
            }
            cur=cur->child[c-'a'];
        }
        return cur->isEnd;
    }
    
    bool startsWith(string prefix) {
        Trie* cur=this;
        for(auto c : prefix){
            if(cur->child[c-'a']==nullptr){
                return false;
            }
            cur=cur->child[c-'a'];
        }
        return true;
    }
};

/**
 * Your Trie object will be instantiated and called as such:
 * Trie* obj = new Trie();
 * obj->insert(word);
 * bool param_2 = obj->search(word);
 * bool param_3 = obj->startsWith(prefix);
 */