问题描述 :
给出一个字符串数组words组成的一本英语词典。从中找出最长的一个单词,该单词是由words词典中其他单词逐步添加一个字母组成。若其中有多个可行的答案,则返回答案中字典序最小的单词。
若无答案,则返回空字符串。
示例 1:
输入:
words = [“w”,“wo”,“wor”,“worl”, “world”]
输出:“world”
解释:
单词"world"可由"w", “wo”, “wor”, 和 “worl"添加一个字母组成。第一个单词是"w”,该单词只有一个字母。我们需要从一个字母的单词开始,每步添加一个字母。
示例 2:
输入:
words = [“a”, “banana”, “app”, “appl”, “ap”, “apply”, “apple”]
输出:“apple”
解释:
“apply"和"apple"都能由词典中的单词组成。但是"apple"的字典序小于"apply”。
输入说明 :
首先输入words数组的长度n,范围为[1,1000]。
然后输入n个字符串,每个字符串长度范围为[1,30]。
所有输入的字符串都只包含小写字母。
输出说明 :
输出答案,不包含空格。
如果没有答案,则输出一个空格。
输入范例 :
7
a banana app appl ap apply apple
输出范例 :
apple
#include<iostream>
#include<vector>
#include<algorithm>
#include<unordered_set>
using namespace std;
bool cmp(string &a,string &b){
return a.length()!=b.length()?a.length()>b.length():a<b;//如果单词长度不同 则按照长度从大到小排
//否则 按照单词字母大小从小到大排序
}
string longestWord(vector<string> &words){
sort(words.begin(),words.end(),cmp);
unordered_set<string> hash;
for(string s:words) hash.insert(s);
for(string s:words){
int len=1;
for( len=1;len<s.length();len++){//利用set在hash中查找 如果没找到 直接跳出循环 否则就将当前值输出
if(hash.find(s.substr(0,len))==hash.end()) break;
}
if(len==s.length()){
return s;
}
}
}
int main(){
int n;
cin>>n;
string str;
vector<string> words;
for(int i=0;i<n;i++){
cin>>str;
words.push_back(str);
}
string res=longestWord(words);
cout<<res;
return 0;
}