Implement Trie(实现 Trie)

http://www.lintcode.com/zh-cn/problem/implement-trie/?rand=true

import java.util.ArrayList;
import java.util.List;

/**
 * Your Trie object will be instantiated and called as such:
 * Trie trie = new Trie();
 * trie.insert("lintcode");
 * trie.search("lint"); will return false
 * trie.startsWith("lint"); will return true
 */


class TrieNode {
    // Initialize your data structure here.
    List list;

    public TrieNode() {
        list = new ArrayList<>();
    }
}

public class Trie {
    private TrieNode root;

    public Trie() {
        // do intialization if necessary
        root = new TrieNode();
    }

    /*
     * @param word: a word
     * @return: nothing
     */
    public void insert(String word) {
        // write your code here
        root.list.add(0, word);
    }

    /*
     * @param word: A string
     * @return: if the word is in the trie.
     */
    public boolean search(String word) {
        // write your code here
        return root.list.contains(word);
    }

    /*
     * @param prefix: A string
     * @return: if there is any word in the trie that starts with the given prefix.
     */
    public boolean startsWith(String prefix) {
        // write your code here
        for (String temp :
                root.list) {
            if (temp.startsWith(prefix)) {
                return true;
            }
        }
        return false;
    }
}

你可能感兴趣的:(Implement Trie(实现 Trie))