leetcode 720 - Longest Word in Dictionary

Posted bella2017

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 720 - Longest Word in Dictionary相关的知识,希望对你有一定的参考价值。

 

技术图片

思路:Brute force + pruning

用不用set来存储输入的words都可以。

class Solution 
public:
    string longestWord(vector<string>& words) 
        string best;  //存储当前最优解
        //unordered_set<string> dict(words.begin(), words.end());
        for(const string& word: words)
            //pruning
            if(word.length()<best.length() || (word.length()==best.length()&& word>best))
                continue;
            string prefix;
            bool valid = true;
            for(int i=0; i<word.length()-1 && valid; ++i)
                prefix += word[i];
                if(find(words.begin(), words.end(), prefix)==words.end())
                //if(!dict.count(prefix))
                    valid = false;
            
            if(valid) best = word;
        
        return best;
    
;

 

以上是关于leetcode 720 - Longest Word in Dictionary的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 720 - Longest Word in Dictionary

720. Longest Word in Dictionary

720. Longest Word in Dictionary

Hash Table-720. Longest Word in Dictionary

720. Longest Word in Dictionary 字典中最长的单词

ARTS第四周打卡