208. 实现 Trie (前缀树)

class Trie {

    Trie[] chs= new Trie[26];
    int cnt = 0;

    public Trie() {

    }
    
    public void insert(String word) {
        Trie root = this;
        for(char ch : word.toCharArray()){
            if(root.chs[ch - 'a'] == null){
                root.chs[ch - 'a'] = new Trie();
            }
            root = root.chs[ch - 'a'];
        }
        root.cnt ++;
    }
    
    public boolean search(String word) {
        Trie root = this;
        for(char ch : word.toCharArray()){
            if(root.chs[ch - 'a'] == null)
                return false;
            root = root.chs[ch - 'a'];
        }
        return root.cnt != 0;
    }
    
    public boolean startsWith(String prefix) {
        Trie root = this;
        for(char ch : prefix.toCharArray()){
            if(root.chs[ch - 'a'] == null)
                return false;
            root = root.chs[ch - 'a'];
        }
        return true;
    }
}
posted @ 2024-04-01 18:26  Shie1d  阅读(3)  评论(0)    收藏  举报