首页 > 代码库 > [LeetCode] 208. Implement Trie (Prefix Tree) Java
[LeetCode] 208. Implement Trie (Prefix Tree) Java
题目:
Implement a trie with insert
, search
, and startsWith
methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z
.
题意及分析:实现一个字典树或者叫前缀树的插入、删除和startsWith判断。这里定义一个trieNode类作为字典树的节点类。然后有一个chilrden数组保存子节点,一个isWord变量来判断从根节点到该节点是否是一个单词。这里我用的是长度为26的数组来保存子节点,浪费了一些内存,也可以用一个hashmap来实现。
代码:
class TrieNode{ public char word; boolean isWord; //记录是否是单词结尾 public TrieNode[] childNodes = new TrieNode[26]; public TrieNode(){}; public TrieNode(char c){ TrieNode node = new TrieNode(); node.word = c; } } public class Trie { private TrieNode root; /** Initialize your data structure here. */ public Trie() { root = new TrieNode(); root.word = ‘ ‘; } /** Inserts a word into the trie. */ public void insert(String word) { TrieNode node = root; for(int i=0;i<word.length();i++){ if(node.childNodes[(word.charAt(i)-‘a‘)]!=null){ node = node.childNodes[(word.charAt(i)-‘a‘)]; }else{ //后面的需要重新创建 for(int j=i;j<word.length();j++){ //重新创建一颗子树 node.childNodes[(word.charAt(j)-‘a‘)] = new TrieNode(word.charAt(j)); node = node.childNodes[(word.charAt(j)-‘a‘)]; } break; //跳出循环 } } node.isWord = true; } /** Returns if the word is in the trie. */ public boolean search(String word) { //要到根节点才能判断,中间的不算 TrieNode node = root; for(int i=0;i<word.length();i++) { if (node.childNodes[(word.charAt(i) - ‘a‘)] != null) { node = node.childNodes[(word.charAt(i) - ‘a‘)]; }else { return false; } } return node.isWord; } /** Returns if there is any word in the trie that starts with the given prefix. */ public boolean startsWith(String prefix) { TrieNode node = root; for(int i=0;i<prefix.length();i++) { if (node.childNodes[(prefix.charAt(i) - ‘a‘)] != null) { node = node.childNodes[(prefix.charAt(i) - ‘a‘)]; }else { return false; } } return true; } } /** * Your Trie object will be instantiated and called as such: * Trie obj = new Trie(); * obj.insert(word); * boolean param_2 = obj.search(word); * boolean param_3 = obj.startsWith(prefix); */
[LeetCode] 208. Implement Trie (Prefix Tree) Java
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。