zoukankan      html  css  js  c++  java
  • 【Leetcode_easy】720. Longest Word in Dictionary

    problem

    720. Longest Word in Dictionary

    题意:

    solution1: BFS;

    class Solution {
    public:
        string longestWord(vector<string>& words) {
            string res = "";
            unordered_set<string> s(words.begin(), words.end());
            queue<string> q;
            for(auto word:words)
            {
                if(word.size()==1) q.push(word);
            }
            int maxLen = 0;
            while(!q.empty())
            {
                string t = q.front();
                q.pop();
                if(t.size()>maxLen) 
                {
                    maxLen = t.size();
                    res = t;//err....
                }
                else if(t.size()==maxLen) res = min(res, t);
                for(char ch='a'; ch<='z'; ++ch)//err...
                {
                    t.push_back(ch);
                    if(s.count(t)) q.push(t);
                    t.pop_back();
                }
            }
            return res;
        }
    };

    solution2:

    class Solution {
    public:
        string longestWord(vector<string>& words) {
            string res = "";
            unordered_set<string> s(words.begin(), words.end());
            int maxLen = 0;
            for (auto word:words)
            {
                if(word.size()==1) helper(s, word, maxLen, res);
            }
            return res;
        }
        void helper(unordered_set<string>& s, string word, int& maxLen, string& res) {
            if(word.size()>maxLen)
            {
                maxLen = word.size();
                res = word;
            }
            else if(word.size()==maxLen) res = min(res, word);
            for(char ch = 'a'; ch<='z'; ++ch)
            {
                word.push_back(ch);
                if(s.count(word)) helper(s, word, maxLen, res);
                word.pop_back();
            }
        }
    };

    参考

    1. Leetcode_easy_720. Longest Word in Dictionary;

    2. Grandyang;

  • 相关阅读:
    java嵌套循环练习
    java菜鸡循环练习
    Kruskal重构树
    狄利克雷卷积
    莫比乌斯反演
    两道趣题
    树状数组
    多重背包
    SPFA与差分约束
    快速线性筛
  • 原文地址:https://www.cnblogs.com/happyamyhope/p/11114849.html
Copyright © 2011-2022 走看看