Leetcode算法学习日志-720 Longest Word in Dictionary

Leetcode 720 Longest Word in Dictionary

题目原文

Given a list of strings words representing an English Dictionary, find the longest word in words that can be built one character at a time by other words in words. If there is more than one possible answer, return the longest word with the smallest lexicographical order.

If there is no answer, return the empty string.

Example 1:

Input: 
words = ["w","wo","wor","worl", "world"]
Output: "world"
Explanation: 
The word "world" can be built one character at a time by "w", "wo", "wor", and "worl".

Example 2:

Input: 
words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
Output: "apple"
Explanation: 
Both "apply" and "apple" can be built from other words in the dictionary. However, "apple" is lexicographically smaller than "apply".

Note:

  • All the strings in the input will only contain lowercase letters.
  • The length of words will be in the range [1, 1000].
  • The length of words[i] will be in the range [1, 30].

题意分析

给定一组string,寻找最长的一个string,使得他由words中的元素逐字母生成,如world,则它逐字母生成意味着w,wo,wor,worl均在words中。如果长度相同,输出字典序较小那个,也就是第一个不同字母字典序较小的那个。

解法分析

本题关键在于对words排序,按长度从大到小排序,长度相同的则按字典从小到大排序,对排好序的words从头检测是否满足题意。为了进行检测,需要将words中的元素放入一个set中(unordered_set较好),每个string的子string是否在set中,知道只有一个字母。C++代码如下:

class Solution {
public:
    static bool myCompare(pair<string,int> &a,pair<string,int> &b){
        if(a.second==b.second)
            return a.first<b.first;
        else
            return a.second>b.second;
    }
    string longestWord(vector<string>& words) {
        vector<pair<string,int>> wordLen;
        set<string> wordSet;
        pair<string,int> temp;
        for(auto w:words){
            temp.first=w;
            temp.second=w.size();
            wordLen.push_back(temp);
            wordSet.insert(w);
        }
        sort(wordLen.begin(),wordLen.end(),myCompare);
        int n;
        for(auto p:wordLen){
            for(n=p.second-1;n>0;n--){
                if(!wordSet.count((p.first).substr(0,n)))
                    break;
            }
            if(n==0)
                return p.first;
        }
        return "";   
    }
};
注意关联容器不能使用sort来进行排序,set和map内部采用红黑树对key进行了排序,但不能对value进行排序,需要排序只能将map放入线性容器中。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值