【LeetCode】208. 實現 Trie (前綴樹)

在這裏插入圖片描述

我的思路是,創建一個StringBuffer,然後每增加一個word比如dog,我就向sb中append:-dog-,搜索一個單詞就搜索-xxx-,搜索前綴,就搜索-xxx

運行速度比較慢。

在這裏插入圖片描述

class Trie {

    private StringBuffer sb;

    /**
     * Initialize your data structure here.
     */
    public Trie() {
        sb = new StringBuffer();
    }

    /**
     * Inserts a word into the trie.
     */
    public void insert(String word) {
        sb.append("-");
        sb.append(word);
        sb.append("-");
    }

    /**
     * Returns if the word is in the trie.
     */
    public boolean search(String word) {
        return sb.toString().contains("-" + word + "-");
    }

    /**
     * Returns if there is any word in the trie that starts with the given prefix.
     */
    public boolean startsWith(String prefix) {
        return sb.toString().contains("-" + prefix);
    }
}

比較好的思路是實現一個字典樹/前綴樹。Trie

在這裏插入圖片描述

// 前綴樹
class Trie {
    private Trie[] links;
    private boolean isEnd;

    public Trie() {
        links = new Trie[26];
    }

    public void insert(String word) {
        Trie node = this;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (node.links[c - 'a'] == null)
                node.links[c - 'a'] = new Trie();
            node = node.links[c - 'a'];
        }
        node.isEnd = true;
    }

    public boolean search(String word) {
        Trie node = this;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (node.links[c - 'a'] == null) {
                return false;
            }
            node = node.links[c - 'a'];
        }
        if (!node.isEnd) return false;
        return true;
    }

    public boolean startsWith(String prefix) {
        Trie node = this;
        for (int i = 0; i < prefix.length(); i++) {
            char c = prefix.charAt(i);
            if (node.links[c - 'a'] == null) {
                return false;
            }
            node = node.links[c - 'a'];
        }
        return true;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章