leetcode [208]Implement Trie (Prefix Tree)
Implement a trie with insert
, search
, and startsWith
methods.
Example:
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // returns true trie.search("app"); // returns false trie.startsWith("app"); // returns true trie.insert("app"); trie.search("app"); // returns true
Note:
- You may assume that all inputs are consist of lowercase letters
a-z
. - All inputs are guaranteed to be non-empty strings.
前缀树的具体实现。
解法:
前缀树的每一个节点保存着当前节点的字符,子节点,从根节点到当前节点是否构成一个词。这道题目里面所有词都是由小写字母组成的,所以子节点的数组大小为24。
java:
public class TrieNode{ public char val; public boolean isWord; public TrieNode[] children=new TrieNode[26]; TrieNode(){} TrieNode(char val){ this.val=val; } } class Trie { public TrieNode root; /** Initialize your data structure here. */ public Trie() { root=new TrieNode(' '); } /** Inserts a word into the trie. */ public void insert(String word) { TrieNode t=root; for(int i=0;i<word.length();i++){ if(t.children[word.charAt(i)-'a']==null){ t.children[word.charAt(i)-'a']=new TrieNode(word.charAt(i)); } t=t.children[word.charAt(i)-'a']; if(i==word.length()-1) t.isWord=true; } } /** Returns if the word is in the trie. */ public boolean search(String word) { TrieNode t=root; for(int i=0;i<word.length();i++){ char c=word.charAt(i); if (t.children[c-'a']==null) return false; t=t.children[c-'a']; if(i==word.length()-1 && t.isWord) return true; } return false; } /** Returns if there is any word in the trie that starts with the given prefix. */ public boolean startsWith(String prefix) { TrieNode t=root; for(int i=0;i<prefix.length();i++){ char c=prefix.charAt(i); if (t.children[c-'a']==null) return false; t=t.children[c-'a']; } return true; } }

更多精彩