208. Implement Trie (Prefix Tree)

Implement a trie with insertsearch, and startsWith methods.
Note:

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

分清trie和trieNode
第一次做的时候 感觉每一个trieNode都可以作为trie 形成了递归的关系 写起来就比较乱 

solution:

class TrieNode {

    // R links to node children
    private TrieNode[] links;

    private final int R = 26;

    private boolean isEnd;

    public TrieNode() {
        links = new TrieNode[R];
    }

    public boolean containsKey(char ch) {
        return links[ch -'a'] != null;
    }
    public TrieNode get(char ch) {
        return links[ch -'a'];
    }
    public void put(char ch, TrieNode node) {
        links[ch -'a'] = node;
    }
    public void setEnd() {
        isEnd = true;
    }
    public boolean isEnd() {
        return isEnd;
    }
}


class Trie {
    private TrieNode root;

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

    // Inserts a word into the trie.
    public void insert(String word) {
        TrieNode node = root;
        for (int i = 0; i < word.length(); i++) {
            char currentChar = word.charAt(i);
            if (!node.containsKey(currentChar)) {
                node.put(currentChar, new TrieNode());
            }
            node = node.get(currentChar);
        }
        node.setEnd();
    }


    // search a prefix or whole key in trie and
    // returns the node where search ends
    private TrieNode searchPrefix(String word) {
        TrieNode node = root;
        for (int i = 0; i < word.length(); i++) {
           char curLetter = word.charAt(i);
           if (node.containsKey(curLetter)) {
               node = node.get(curLetter);
           } else {
               return null;
           }
        }
        return node;
    }

    // Returns if the word is in the trie.
    public boolean search(String word) {
       TrieNode node = searchPrefix(word);
       return node != null && node.isEnd();
    }

     // Returns if there is any word in the trie
    // that starts with the given prefix.
    public boolean startsWith(String prefix) {
        TrieNode node = searchPrefix(prefix);
        return node != null;
    }
}

自己的和solution还有一点主要的区别 对于子节点 solution用的是char数组 我用的是set 
时间复杂度是相同的 但空间复杂度上 显然我的会比较高
因为hashset实际上是封装的hashmap hashmap底层是链表的数组 为避免hash冲突 会开辟比较大的空间
对于这点 题目其实也有提示 
You may assume that all inputs are consist of lowercase letters a-z.

所以当需要map或者set 但是元素只有字母的时候 你可以使用数组来代替
比如 先要统计一个非常长的单词每个字母出现的次数 首先会想到hashmap
但实际上使用一个长度为26的int数组就可以了
int[] map = new int[26];
map[0]表示a出现的次数 map[1]表示b出现的次数 。。。
获取索引及对应的值也非常方便
比如 f出现的次数对应的值 索引就是 ’f’-‘a’ = 5 出现的次数就是map[5] 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值