Leetcode 720 Longest Word in Dictionary
题目原文
Given a list of strings words
representing an English Dictionary, find the longest word in words
that can be built one character at a time by other words in words
. If there is more than one possible answer, return the longest word with the smallest lexicographical order.
Example 1:
Input:
words = ["w","wo","wor","worl", "world"]
Output: "world"
Explanation:
The word "world" can be built one character at a time by "w", "wo", "wor", and "worl".
Example 2:
Input:
words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
Output: "apple"
Explanation:
Both "apply" and "apple" can be built from other words in the dictionary. However, "apple" is lexicographically smaller than "apply".
Note:
- All the strings in the input will only contain lowercase letters.
- The length of
words
will be in the range[1, 1000]
. - The length of
words[i]
will be in the range[1, 30]
.
题意分析
给定一组string,寻找最长的一个string,使得他由words中的元素逐字母生成,如world,则它逐字母生成意味着w,wo,wor,worl均在words中。如果长度相同,输出字典序较小那个,也就是第一个不同字母字典序较小的那个。
解法分析
本题关键在于对words排序,按长度从大到小排序,长度相同的则按字典从小到大排序,对排好序的words从头检测是否满足题意。为了进行检测,需要将words中的元素放入一个set中(unordered_set较好),每个string的子string是否在set中,知道只有一个字母。C++代码如下:
class Solution {
public:
static bool myCompare(pair<string,int> &a,pair<string,int> &b){
if(a.second==b.second)
return a.first<b.first;
else
return a.second>b.second;
}
string longestWord(vector<string>& words) {
vector<pair<string,int>> wordLen;
set<string> wordSet;
pair<string,int> temp;
for(auto w:words){
temp.first=w;
temp.second=w.size();
wordLen.push_back(temp);
wordSet.insert(w);
}
sort(wordLen.begin(),wordLen.end(),myCompare);
int n;
for(auto p:wordLen){
for(n=p.second-1;n>0;n--){
if(!wordSet.count((p.first).substr(0,n)))
break;
}
if(n==0)
return p.first;
}
return "";
}
};
注意关联容器不能使用sort来进行排序,set和map内部采用红黑树对key进行了排序,但不能对value进行排序,需要排序只能将map放入线性容器中。