持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第22天,点击查看活动详情
一、题目描述:
给出一个字符串数组 words 组成的一本英语词典。返回 words 中最长的一个单词,该单词是由 words 词典中其他单词逐步添加一个字母组成。
若其中有多个可行的答案,则返回答案中字典序最小的单词。若无答案,则返回空字符串。
示例 1:
输入:words = ["w","wo","wor","worl", "world"]
输出:"world"
解释: 单词"world"可由"w", "wo", "wor", 和 "worl"逐步添加一个字母组成。
示例 2:
输入:words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
输出:"apple"
解释:"apply" 和 "apple" 都能由词典中的单词组成。但是 "apple" 的字典序小于 "apply"
提示:
- 1 <= words.length <= 1000
- 1 <= words[i].length <= 30
- 所有输入的字符串 words[i] 都只包含小写字母。
二、思路分析:
最长单词 长度相等返回字典序小的。
数组长度n,字符平均长度l,数组字符总长度为s。 建树trie时间 s,查询时间也是s,故时间复杂度为s。 search时这句代码要注意。 if( p->son[u]==nullptr || p->son[u]->isend==false) return false;
如果对字符串排序,长度升序,长度相等字典序降序。排序时间是 slogn。 排序+ 哈希,时间slogn,时间复杂度高但代码短。实测时间短。
三、AC 代码:
class Trie{
private:
vector<Trie*> son;
bool isend;
public:
Trie(){
son = vector<Trie*>(26, nullptr);
isend = false;
}
void insert(string w){
Trie* p = this;
for(auto& c: w){
int u = c-'a';
if( p->son[u]==nullptr) p->son[u]= new Trie();
p = p->son[u];
}
p->isend = true;
}
bool search(string w){
Trie* p = this;
for(auto& c: w){
int u = c-'a';
if( p->son[u]==nullptr || p->son[u]->isend==false) return false; //
p = p->son[u];
}
return p!=nullptr && p->isend;
}
};
class Solution {
public:
string longestWord(vector<string> ws){
auto cmp = [](const string& a, const string& b){
return a.size()!= b.size()? a.size()< b.size(): a>b;
};
sort(ws.begin(), ws.end(), cmp);
unordered_set<string> wset;
wset.insert("");
string res="";
for(auto& w: ws){
if( wset.count( w.substr(0, w.size()-1))>0){
wset.insert(w);
res = w;
}
}
return res;
};
范文参考:
本题关键:lambda x: (len(x), x) 从长度和字典序对列表排序 - 词典中最长的单词 - 力扣(LeetCode)