码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 208 Implement Trie (Prefix Tree)

时间:2016-08-24 11:23:33      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

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

Note:
You may assume that all inputs are consist of lowercase letters a-z.


题目链接:https://leetcode.com/problems/implement-trie-prefix-tree/

题目分析:实现一个字典树,每个节点有26个孩子[a - z]

class TrieNode {
    // Initialize your data structure here.
    final int SIZE = 26;
    boolean isWord;
    boolean isPrefix;
    TrieNode[] next;
    public TrieNode() {
        isWord = false;
        isPrefix = false;
        next = new TrieNode[SIZE];
        for(int i = 0; i < SIZE; i ++) {
            next[i] = null;
        }
    }
}

public class Trie {
    private TrieNode root;

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

    // Inserts a word into the trie.
    public void insert(String word) {
        int len = word.length();
        TrieNode p = new TrieNode();
        p = root;
        for(int i = 0; i < len; i++) {
            int idx = word.charAt(i) - 'a';
            if(p.next[idx] == null) {
                p.next[idx] = new TrieNode();
            }
            p = p.next[idx];
            p.isPrefix = true;
        }
        p.isWord = true;
        return;
    }

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

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

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



LeetCode 208 Implement Trie (Prefix Tree)

标签:

原文地址:http://blog.csdn.net/tc_to_top/article/details/52297991

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!