题目
208. 实现 Trie (前缀树)
720. 词典中最长的单词
思路和解答
📌208. 实现 Trie (前缀树)
class Trie {
class TrieNode{
boolean end; //标识是否是接收字符的结束
TrieNode[] next =new TrieNode[26]; //初始化都为null
}
TrieNode root;
//构造函数
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
TrieNode p = root;
for(int i=0;i<word.length();i++){
int t = word.charAt(i)-'a';
if(p.next[t]==null){
p.next[t] = new TrieNode();
}
p = p.next[t];
}
p.end = true; //标记结束
}
public boolean search(String word) {
TrieNode p = root;
for(int i=0;i<word.length();i++){
int t = word.charAt(i)-'a';
if(p.next[t]==null){
return false;
}
p = p.next[t];
}
return p.end;
}
public boolean startsWith(String prefix) {
TrieNode p = root;
for(int i=0;i<prefix.length();i++){
int t = prefix.charAt(i)-'a';
if(p.next[t]==null){
return false;
}
p = p.next[t];
}
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);
*/
📌
题解:力扣
方法一 时空复杂度粗略写成O(n^2)
class Solution {
public String longestWord(String[] words) {
//用时15分钟
//按字典序从小到大 长度从大到小排序
Arrays.sort(words,(a,b)->{
if(a.length()==b.length()) return a.compareTo(b);
else return b.length()-a.length();
});
Set<String> st = new HashSet<>();
for(String word:words){
st.add(word);
}
for(String word:words){
boolean flag = true;
for(int i=1;i<=word.length();i++){
if(!st.contains(word.substring(0,i))){ //如果一个字符串的所有前缀都被包含则直接返回
flag = false;
break;
}
}
if(flag) return word;
}
return "";
}
}
方法二:前缀树 dfs