zoukankan      html  css  js  c++  java
  • Leetcode720.Longest Word in Dictionary词典中最长的单词

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

    bool cmp1(string a, string b)
    {
        return a.size() > b.size();
    }
    
    bool cmp2(string a, string b)
    {
        return a < b;
    }
    
    class Solution {
    public:
        string longestWord(vector<string>& words) {
            int len = words.size();
            if(len <= 1)
                return len == 0? "":words[0];
            vector<string> res;
            map<string, int> check;
            for(int i = 0; i < len; i++)
            {
                check[words[i]] = 1;
            }
            sort(words.begin(), words.end(), cmp1);
            int MAXsize = 0;
            for(int i = 0; i < len; i++)
            {
                int size = words[i].size();
                bool flag = true;
                if(MAXsize != 0 && MAXsize > size)
                    continue;
                for(int j = 0; j < size - 1; j++)
                {
                    string temp = "";
                    for(int k = 0; k <= j; k++)
                    {
                        temp += words[i][k];
                    }
                    if(check[temp] != 1)
                    {
                        flag = false;
                        break;
                    }
                }
                if(flag == true)
                {
                    MAXsize = max(MAXsize, size);
                    res.push_back(words[i]);
                }
            }
            if(res.size() == 0)
                return "";
            sort(res.begin(), res.end(), cmp2);
            return res[0];
        }
    };
  • 相关阅读:
    php环境配置中各个模块在网站建设中的功能
    PHP+Apache+MySQL+phpMyAdmin在win7系统下的环境配置
    August 17th 2017 Week 33rd Thursday
    August 16th 2017 Week 33rd Wednesday
    August 15th 2017 Week 33rd Tuesday
    August 14th 2017 Week 33rd Monday
    August 13th 2017 Week 33rd Sunday
    August 12th 2017 Week 32nd Saturday
    August 11th 2017 Week 32nd Friday
    August 10th 2017 Week 32nd Thursday
  • 原文地址:https://www.cnblogs.com/lMonster81/p/10433990.html
Copyright © 2011-2022 走看看