Leetcode 208. Implement Trie (Prefix Tree)

Implement a trie with insert, search, and startsWith methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z.

思路:
定義一個節(jié)點表示TrieNode,由于題目說明只有a-z,因此子節(jié)點用一個26長度的數(shù)組即可,此外用一個bool變量表示到當前節(jié)點為止是否為一個單詞。

public class GJ_TrieTree {
class TrieNode {
    public char c;
    public TrieNode[] children;
    public boolean isWord;

    public TrieNode(char c) {
        this.c = c;
        this.children = new TrieNode[256];
        this.isWord = false;
    }
}

public TrieNode root;

/** Initialize your data structure here. */
public Trie() {
    this.root = new TrieNode('0');
}

/** Inserts a word into the trie. */
public void insert(String word) {
    TrieNode dummy = this.root;
    for (int i = 0; i < word.length(); i++) {
        char c = word.charAt(i);
        if (dummy.children[c] == null) {
            dummy.children[c] = new TrieNode(c);
        }
        dummy = dummy.children[c];
    }
    dummy.isWord = true;
}

/** Returns if the word is in the trie. */
public boolean search(String word) {
    TrieNode res = this.findHelper(word);
    return (res != null && res.isWord);
}

/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
    return (this.findHelper(prefix) != null);
}

private TrieNode findHelper(String str) {
    TrieNode dummy = this.root;

    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);
        if (dummy.children[c] == null) {
            return null;
        }
        dummy = dummy.children[c];
    }

    return dummy;
}

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容