|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
题目描述:
- 给出一个字符串数组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"。
-  
- 提示:
- 所有输入的字符串都只包含小写字母。
- words数组长度范围为[1,1000]。
- words[i]的长度范围为[1,30]。
- 来源:力扣(LeetCode)
- 链接:https://leetcode-cn.com/problems/longest-word-in-dictionary
- 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
复制代码
- class Solution {
- public:
- struct TrieTree{
- bool flag;
- map<char, TrieTree*>next;
- TrieTree():flag(false){};
- };
- void dfs(TrieTree* cur_node, string&res, string temp){
- if(cur_node == NULL ||cur_node -> flag == false)return;
- if(temp.size() > res.size())res = temp;
- for(auto cha : cur_node -> next){
- dfs(cur_node -> next[cha.first], res, temp + cha.first);
- }
- }
- string longestWord(vector<string>& words) {
- //构建字典树
- TrieTree* root = new TrieTree();
- for(auto word : words){
- TrieTree* node = root;
- for(auto cha : word){
- if((node -> next).count(cha) == 0){
- node -> next[cha] = new TrieTree();
- }
- node = node -> next[cha];
- }
- node -> flag = true;
- }
- //深度优先搜索
- string res;
- for(auto cha : root ->next){
- if(root -> next[cha.first] -> flag == true){
- string temp;
- dfs(root -> next[cha.first], res, temp + cha.first);
- }
- }
- return res;
- }
- };
复制代码 |
评分
-
查看全部评分
|