网络编程
位置:首页>> 网络编程>> Go语言>> go语言LeetCode题解720词典中最长的单词

go语言LeetCode题解720词典中最长的单词

作者:刘09k11  发布时间:2023-08-05 19:46:04 

标签:go,LeetCode,词典,最长单词

一 描述

720. 词典中最长的单词 - 力扣(LeetCode) (leetcode-cn.com)

给出一个字符串数组 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] 都只包含小写字母。

二 分析

由于题目要求求解最长单词且其前缀都存在在words中,由此可以利用一个hashmap来保存每一个字串,当然也可以采用set来做。然后再遍历整个字串容器,对于每个字串,只要其长度大于或等于max length,那么就需要分别做处理:

word length > max length:

  • 1、先判断这个字串是否符合要求,即它的前缀是否都在words里面;

  • 2、如果不符合要求,则忽略;如果符合要求,则保存。

  • 3、更新max length的信息。

word length == max length:

  • 1、先判断这个字串是否符合要求,即它的前缀是否都在words里面;

  • 2、如果不符合要求,则忽略;如果符合要求,则保存。

  • 3、比较当前两个长度相等的字串,选择字典序小的那个保存。

三 答案

class Solution {
public:
   string longestWord(vector<string>& words) {
       if( words.size() == 0 ){
           return NULL;
       }
unordered_map<string, int> hashWord;
for( auto& hw : words ){
++hashWord[hw];
}
int maxLength = 0;
string word = "";
for( auto& w : words ){
if( maxLength < w.length() ){
bool cntFlag = false;
string strW = "";
for( int i = 0; i < w.length(); ++i ){
strW += w[i];
if( !hashWord.count( strW ) ){
cntFlag = true;
break;
}
}
if( !cntFlag ){
word = "";
word = w;
maxLength = w.length();
}
}else if( maxLength == w.length() ){
bool cntFlag = false;
string strW = "";
for( int i = 0; i < maxLength; ++i ){
strW += w[i];
cout << strW << endl;
if( !hashWord.count( strW ) ){
cntFlag = true;
break;
}
}
if( !cntFlag ){
for( int i = 0; i < maxLength; ++i ){
if( word[i] < w[i] ){
break;
}else if( word[i] > w[i] ){
word = "";
word = w;
}
}
}
}
}
return word;
   }
};

四 总结

此方法比较笨,但也比较容易理解。

来源:https://juejin.cn/post/7179621695806767159

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com