题目链接:
力扣https://leetcode-cn.com/problems/longest-word-in-dictionary/
【分析】利用排序+哈希表来做,先把所有单词加入哈希表,这样后面查找单词的前缀在不在就直接用O(1)的时间就行,然后将单词按照长度和字典序进行排序,从头遍历第一个符合条件的肯定是字典序最小的。
class Solution {
public class StringComparator implements Comparator<String>{
@Override
public int compare(String str1, String str2){
if(str1.length() > str2.length()) return -1;
else if(str1.length() == str2.length() && str1.compareTo(str2) < 0) return -1;
return 1;
}
}
public String longestWord(String[] words) {
Set<String> set = new HashSet<>();
for(String str: words) set.add(str);
Arrays.sort(words, new StringComparator());
int i, n, flag = 1;
String tmp;
for(String str: words){
n = str.length();
flag = 1;
for(i = 1; i < n; i++){
tmp = str.substring(0, i);
if(!set.contains(tmp)){
flag = 0; break;
}
}
if(flag == 1) return str;
}
return "";
}
}
【字典树】
class Solution {
public class Trie{
Map<Character, Trie> map = new HashMap<>();
boolean is_end = false;
public void insert(String word){
Trie cur = this;
int n = word.length();
char c;
for(int i = 0; i < n; i++){
c = word.charAt(i);
if(cur.map.containsKey(c)) cur = cur.map.get(c);
else{
cur.map.put(c, new Trie());
cur = cur.map.get(c);
}
}
cur.is_end = true;
}
}
int max = -1;
String ans = "";
public void dfs(Trie trie, String str){
if(!trie.is_end) return;
if(trie.is_end){
if(str.length() > max) {
max = str.length();
ans = str;
}else if(str.length() == max){
if(str.compareTo(ans) < 0)
ans = str;
}
}
for(Map.Entry<Character, Trie> entry: trie.map.entrySet()){
dfs(entry.getValue(), str + entry.getKey());
}
}
public String longestWord(String[] words) {
int n = words.length, i;
Trie trie = new Trie();
trie.is_end = true;
for(i = 0; i < n; i++){
trie.insert(words[i]);
}
dfs(trie, "");
System.out.println(ans);
return ans;
}
}