网站首页 文章专栏 词典中最长的单词
词典中最长的单词
创建于:2020-07-09 16:00:00 更新于:2024-03-29 10:13:26 羽瀚尘 766
算法题目 算法题目

leetcode题号:720

给出一个字符串数组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]。

解答一

先将原字符数组按升序排列,然后从左到右遍历。 如果当前单词长度为1,或者能在合法单词哈希表中查到前缀,就加入合法单词哈希表

class Solution {
public:
    string longestWord(vector<string>& words) {
        unordered_map<string, int> myhash;
        sort(words.begin(), words.end());
        string res;
        int max_size = 0;
        for(auto &m : words){
            if(m.size() == 1 || myhash.find(m.substr(0, m.size() - 1)) != myhash.end()){
                myhash.insert(pair<string, int>(m, 0));
                if(m.size() > max_size){
                    res = m;
                    max_size = m.size();
                }
            }
        }
        return res;
    }
};

注意,我认为该题应该明确说明所有单词都只能从长度为1的单词开始加,不然像["ap", "app"]的答案应该为"app", 因为它也是由其他单词添加了一个字母组成的。

注意: 此处用哈希表,或者用字典,其时间复杂度要好于用set。

解答二

使用最长前缀树,该树的具体构造需要再研究。

20200709184940

class TrieNode {
public: 
    bool is_word;
    vector<TrieNode*> children;
    TrieNode() : is_word(false), children(26, nullptr){}
    ~TrieNode(){
        for(TrieNode* child : children) if(child) delete child;
    }
};

class Solution {
public:
    string res_str;
    TrieNode* trie_root;
    string longestWord(vector<string>& words) {
        trie_root = new TrieNode();
        for(auto &word : words) add_word(word);
        string temp_str = "";
        my_find(trie_root, temp_str);
        return res_str;
    }
    void add_word(string &word){
        TrieNode *ptr = trie_root;
        for(auto ch : word){
            if(ptr->children[ch - 'a'] == NULL){
                ptr->children[ch - 'a'] = new TrieNode();
            }
            ptr = ptr->children[ch - 'a'];
        }
        ptr->is_word = true;
    }
    void my_find(TrieNode *root, string &res_word){
        if(root != NULL){
            for(int index = 0; index < 26; index++){
                if(root->children[index] != NULL && root->children[index]->is_word){
                    string new_str = res_word + char('a' + index);
                    if(new_str.size() > res_str.size()) res_str = new_str;
                    my_find(root->children[index], new_str);
                }
            }
        }
    }

};