208. Implement Trie (Prefix Tree

2016-12-26  本文已影响0人  FlynnLWang

Question

Implement a trie with insert, search, and startsWith methods.

Code

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

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 node = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (!node.sons.containsKey(c)) {
                TrieNode newSon = new TrieNode();
                newSon.c = c;
                node.sons.put(c, newSon);
            }
            node = node.sons.get(c);
        }
        node.end = true;
    }

    // Returns if the word is in the trie.
    public boolean search(String word) {
        if (word == null || word.length() == 0) return true;
        TrieNode node = root;
        
        boolean re = false;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (node.sons.containsKey(c)) {
                node = node.sons.get(c);
            } else {
                return false;
            }
        }
        if (node.end) re = true;
        return re;
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    public boolean startsWith(String prefix) {
        if (prefix == null || prefix.length() == 0) return true;
        TrieNode node = root;
        
        boolean re = false;
        for (int i = 0; i < prefix.length(); i++) {
            char c = prefix.charAt(i);
            if (node.sons.containsKey(c)) {
                node = node.sons.get(c);
            } else {
                return false;
            }
        }
        re = true;
        return re;
    }
}

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

Solution

实现一颗字典树。 常规方法。

上一篇下一篇

猜你喜欢

热点阅读