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é)點(diǎn)表示TrieNode,由于題目說明只有a-z,因此子節(jié)點(diǎn)用一個26長度的數(shù)組即可,此外用一個bool變量表示到當(dāng)前節(jié)點(diǎn)為止是否為一個單詞。

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)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容