Leetcode - Implement Trie (Prefix Tree)

My code:

class TrieNode {
    // Initialize your data structure here.
    char c;
    boolean isLeaf;
    HashMap<Character, TrieNode> tracker = new HashMap<Character, TrieNode>();
    public TrieNode() {
        
    }
}

public class Trie {
    private TrieNode root;

    public Trie() {
        root = new TrieNode();
    }

    // Inserts a word into the trie.
    public void insert(String word) {
        if (word == null || word.length() == 0)
            return;
        TrieNode temp = root;
        for (int i = 0; i < word.length(); i++) {
            char curr = word.charAt(i);
            if (temp.tracker.containsKey(curr)) {
                temp = temp.tracker.get(curr);
            }
            else {
                TrieNode newNode = new TrieNode();
                newNode.c = curr;
                temp.tracker.put(curr, newNode);
                temp = newNode;
            }
            if (i == word.length() - 1) {
                temp.isLeaf = true;
            }
        }
    }

    // Returns if the word is in the trie.
    public boolean search(String word) {
        TrieNode ret = searchNode(word);
        if (ret == null || !ret.isLeaf)
            return false;
        else
            return true;
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    public boolean startsWith(String prefix) {
        TrieNode ret = searchNode(prefix);
        return ret == null ? false : true;
    }
    
    private TrieNode searchNode(String word) {
        if (word == null || word.length() == 0)
            return null;
        TrieNode temp = root;
        for (int i = 0; i < word.length(); i++) {
            char curr = word.charAt(i);
            if (!temp.tracker.containsKey(curr)) {
                return null;
            }
            else {
                temp = temp.tracker.get(curr);
            }
        }
        return temp;
    }
}

// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");

之前寫過trie。今天為了節(jié)省時(shí)間鸽素,直接看了答案再自己重寫了一遍。
http://www.programcreek.com/2014/05/leetcode-implement-trie-prefix-tree-java/

Anyway, Good luck, Richardo!

My code:

class TrieNode {
    // Initialize your data structure here.
    TrieNode[] next;
    char val;
    boolean isWord;
    public TrieNode() {
        next = new TrieNode[26];
    }
}

public class Trie {
    private TrieNode root;

    public Trie() {
        root = new TrieNode();
    }

    // Inserts a word into the trie.
    public void insert(String word) {
        insert(word, 0, root);
    }
    
    private void insert(String word, int index, TrieNode root) {
        char curr = word.charAt(index);
        TrieNode nextNode = null;
        if (root.next[curr -'a'] != null) {
            nextNode = root.next[curr - 'a'];
        }
        else {
            nextNode = new TrieNode();
            root.next[curr - 'a'] = nextNode;
        }
        if (index == word.length() - 1) {
            nextNode.isWord = true;
            return;
        }
        insert(word, index + 1, nextNode);
        
    }

    // Returns if the word is in the trie.
    public boolean search(String word) {
        TrieNode next = root;
        for (int i = 0; i < word.length(); i++) {
            char curr = word.charAt(i);
            if (next.next[curr - 'a'] == null) {
                return false;
            }
            else {
                next = next.next[curr - 'a'];
            }
        }
        return next.isWord;
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    public boolean startsWith(String prefix) {
        TrieNode next = root;
        for (int i = 0; i < prefix.length(); i++) {
            char curr = prefix.charAt(i);
            if (next.next[curr - 'a'] == null) {
                return false;
            }
            else {
                next = next.next[curr - 'a'];
            }
        }
        return true;
    }
}

// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");

差不多的思路吧垫挨。
reference:
https://leetcode.com/articles/implement-trie-prefix-tree/

Anyway, Good luck, Richardo! -- 09/11/2016

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末跛溉,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子砰碴,更是在濱河造成了極大的恐慌躏筏,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,734評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件呈枉,死亡現(xiàn)場離奇詭異趁尼,居然都是意外死亡埃碱,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,931評論 3 394
  • 文/潘曉璐 我一進(jìn)店門酥泞,熙熙樓的掌柜王于貴愁眉苦臉地迎上來砚殿,“玉大人,你說我怎么就攤上這事芝囤∷蒲祝” “怎么了?”我有些...
    開封第一講書人閱讀 164,133評論 0 354
  • 文/不壞的土叔 我叫張陵悯姊,是天一觀的道長羡藐。 經(jīng)常有香客問我,道長挠轴,這世上最難降的妖魔是什么传睹? 我笑而不...
    開封第一講書人閱讀 58,532評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮岸晦,結(jié)果婚禮上欧啤,老公的妹妹穿的比我還像新娘。我一直安慰自己启上,他們只是感情好邢隧,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,585評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著冈在,像睡著了一般倒慧。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上包券,一...
    開封第一講書人閱讀 51,462評論 1 302
  • 那天纫谅,我揣著相機(jī)與錄音,去河邊找鬼溅固。 笑死付秕,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的侍郭。 我是一名探鬼主播询吴,決...
    沈念sama閱讀 40,262評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼亮元!你這毒婦竟也來了猛计?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,153評論 0 276
  • 序言:老撾萬榮一對情侶失蹤爆捞,失蹤者是張志新(化名)和其女友劉穎奉瘤,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體嵌削,經(jīng)...
    沈念sama閱讀 45,587評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡毛好,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,792評論 3 336
  • 正文 我和宋清朗相戀三年望艺,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了苛秕。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片肌访。...
    茶點(diǎn)故事閱讀 39,919評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖艇劫,靈堂內(nèi)的尸體忽然破棺而出吼驶,到底是詐尸還是另有隱情,我是刑警寧澤店煞,帶...
    沈念sama閱讀 35,635評論 5 345
  • 正文 年R本政府宣布蟹演,位于F島的核電站,受9級特大地震影響顷蟀,放射性物質(zhì)發(fā)生泄漏酒请。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,237評論 3 329
  • 文/蒙蒙 一鸣个、第九天 我趴在偏房一處隱蔽的房頂上張望羞反。 院中可真熱鬧,春花似錦囤萤、人聲如沸昼窗。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,855評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽澄惊。三九已至,卻和暖如春富雅,著一層夾襖步出監(jiān)牢的瞬間掸驱,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,983評論 1 269
  • 我被黑心中介騙來泰國打工没佑, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留毕贼,地道東北人。 一個月前我還...
    沈念sama閱讀 48,048評論 3 370
  • 正文 我出身青樓图筹,卻偏偏與公主長得像帅刀,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子远剩,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,864評論 2 354

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