【Leetcode】208. Implement Trie (Prefix Tree)

題目地址:

https://leetcode.com/problems/implement-trie-prefix-tree/

實現字典樹Trie,實現插入單詞,查找某單詞是否存在,查找是否存在以某個字符串爲前綴的單詞。

想象有個node作爲樹根,然後樹根下分出幾個分叉,邊上代表字母,然後連到下一個node上,這個node也可以以相同方式連接到更下面的node上。node裏只需存放其向下有哪些邊,邊對應着什麼字母,以及邊連到的node的指針,這個可以用一個哈希表實現;此外node裏還應該存放到這個node爲止代表的單詞是否在Trie裏,所以要有一個boolean變量記錄這個信息。具體代碼如下:

import java.util.HashMap;
import java.util.Map;

public class Trie {
    // 字典樹的節點的類
    class Node {
    	// 記錄從樹根到該節點的路徑表示的單詞是否在字典樹裏
        boolean isWord;
        // next表示該node有哪些分叉,每個分叉代表的字母和連接到的node
        Map<Character, Node> next;
    
        public Node() {
            next = new HashMap<>();
        }
    }
    
    Node root;
    
    /** Initialize your data structure here. */
    public Trie() {
        root = new Node();
    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        Node cur = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            // 先看有沒有c這條邊,如果沒有,就添加一下
            if (!cur.next.containsKey(c)) {
                cur.next.put(c, new Node());
            }
            // 取出這條邊連到的節點
            cur = cur.next.get(c);
        }
        // 最後標記一下這個節點終止處存在單詞
        cur.isWord = true;
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        Node cur = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (!cur.next.containsKey(c)) {
                return false;
            }
            cur = cur.next.get(c);
        }
        
        return cur.isWord;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        Node cur = root;
        for (int i = 0; i < prefix.length(); i++) {
            char c = prefix.charAt(i);
            if (!cur.next.containsKey(c)) {
                return false;
            }
            cur = cur.next.get(c);
        }
        
        return true;
    }
}

時間複雜度都是O(n)O(n),空間複雜度O(n)O(n),看單詞長度。

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