classTrie{private StringBuffer sb;/**
* Initialize your data structure here.
*/publicTrie(){
sb =newStringBuffer();}/**
* Inserts a word into the trie.
*/publicvoidinsert(String word){
sb.append("-");
sb.append(word);
sb.append("-");}/**
* Returns if the word is in the trie.
*/publicbooleansearch(String word){return sb.toString().contains("-"+ word +"-");}/**
* Returns if there is any word in the trie that starts with the given prefix.
*/publicbooleanstartsWith(String prefix){return sb.toString().contains("-"+ prefix);}}
比較好的思路是實現一個字典樹/前綴樹。Trie
// 前綴樹classTrie{private Trie[] links;privateboolean isEnd;publicTrie(){
links =newTrie[26];}publicvoidinsert(String word){
Trie node =this;for(int i =0; i < word.length(); i++){char c = word.charAt(i);if(node.links[c -'a']== null)
node.links[c -'a']=newTrie();
node = node.links[c -'a'];}
node.isEnd =true;}publicbooleansearch(String word){
Trie node =this;for(int i =0; i < word.length(); i++){char c = word.charAt(i);if(node.links[c -'a']== null){returnfalse;}
node = node.links[c -'a'];}if(!node.isEnd)returnfalse;returntrue;}publicbooleanstartsWith(String prefix){
Trie node =this;for(int i =0; i < prefix.length(); i++){char c = prefix.charAt(i);if(node.links[c -'a']== null){returnfalse;}
node = node.links[c -'a'];}returntrue;}}