class Solution {
public String longestWord(String[] words) {
Trie root =new Trie();
for (String word : words) {
Trie cur =root;
for (char c : word.toCharArray()) {
if (cur.childeren.containsKey(c)) {
cur =cur.childeren.get(c);
}
else{
Trie temp = new Trie();
cur.childeren.put(c,temp);
cur =temp;
}
}
cur.val =word;
cur.isEnd =true;
}
String result ="";
for (String word : words) {
Trie cur =root;
if (word.length()>result.length() || (word.length() == result.length() && word.compareTo(result) <0)) {
boolean isWord =true;
for (char c :word.toCharArray()) {
cur =cur.childeren.get(c);
if (!cur.isEnd) {
isWord =false;
break;
}
}
result =isWord ? word : result;
}
}
return result;
}
}
class Trie {
public HashMap<Character,Trie> childeren = new HashMap();
public String val =null;
public boolean isEnd =false;
}