题目大意:给出字典中的一些字符串,找出他们中的最长单词,使得这个单词由字典中的字符串逐字母生成,如果长度相同取字典序较小的一个。
分析:trie应用。或者用集合set来做。
方法一集合:字符串sort排序后是按长度由小到大,字典序由小到大排列的。取出words中的一个字符串,如果它长度为1或者取出它的长度减一的子串在built集合中,就更新答案,并将当前取出的字符串放入built集合中。built集合相当于一个满足我们题意要求的字符串集合,也就是里面插入的字符串都是逐个字母堆砌出来的。
代码:
方法一:集合 转载自http://blog.youkuaiyun.com/zy2317878/article/details/79056154
class Solution {
public:
string longestWord(vector<string>& words) {
sort(words.begin(), words.end());
unordered_set<string> built;
string res;
for (string w : words) {
if (w.size() == 1 || built.count(w.substr(0, w.size() - 1))) { //substr(0,n)从0起取多少个字符
res = w.size() > res.size() ? w : res;
built.insert(w);
}
}
return res;
}
};
方法二:trie JAVA代码转载自https://leetcode.com/problems/longest-word-in-dictionary/solution/
class Solution {
public String longestWord(String[] words) {
Trie trie = new Trie();
int index = 0;
for (String word: words) {
trie.insert(word, ++index); //indexed by 1
}
trie.words = words;
return trie.dfs();
}
}
class Node {
char c;
HashMap<Character, Node> children = new HashMap();
int end;
public Node(char c){
this.c = c;
}
}
class Trie {
Node root;
String[] words;
public Trie() {
root = new Node('0');
}
public void insert(String word, int index) {
Node cur = root;
for (char c: word.toCharArray()) {
cur.children.putIfAbsent(c, new Node(c));
cur = cur.children.get(c);
}
cur.end = index;
}
public String dfs() {
String ans = "";
Stack<Node> stack = new Stack();
stack.push(root);
while (!stack.empty()) {
Node node = stack.pop();
if (node.end > 0 || node == root) {
if (node != root) {
String word = words[node.end - 1];
if (word.length() > ans.length() ||
word.length() == ans.length() && word.compareTo(ans) < 0) {
ans = word;
}
}
for (Node nei: node.children.values()) {
stack.push(nei);
}
}
}
return ans;
}
}