Leetcode 524. Longest Word in Dictionary through Deleting

本文解析了LeetCode 524题,旨在寻找给定字符串数组中最长且字典序最小的子串,可通过删除给定字符串的部分字符得到。介绍了两种解题思路,一种是对字符串数组进行预排序,另一种是在遍历过程中动态更新最长匹配子串。

Leetcode 524. Longest Word in Dictionary through Deleting

Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.

Example 1:
Input:
s = “abpcplea”, d = [“ale”,“apple”,“monkey”,“plea”]
Output:
“apple”

Example 2:
Input:
s = “abpcplea”, d = [“a”,“b”,“c”]
Output:
“a”

题目大意:给定一个字符串数组d和字符串s,返回d中长度最大字典序最小的可以由s通过删除若干字母所组成的单词(查找子串)。如果没有则返回空。

解题思路1:
首先对字符串数组d进行长度由长到短,等长则字典序大小由小到大的方式进行排序。之后从d按取出字符串d[i],设置两个指针p,q分别指向字符串s和d[i]的首个元素。比较s[p]和d[i][q],由于已经将d排序,则第一个符合匹配条件的元素即为答案。如果两者相等则指针同时后移,如果不等,则p后移;若q等于d[i]的长度,则说明该d[i]符合条件。时间复杂度为O(nxlogn + nx),其中n为d中元素数量,x为字符串s的平均长度。

代码:

class Solution {
    static int comp(string a, string b)
        {
            if(a.length() == b.length())
                return a < b;
            else
                return a.length() > b.length();
        }
public:
    string findLongestWord(string s, vector<string>& d) {
        sort(d.begin(), d.end(), comp);
        for(int i = 0; i < d.size(); i++)
        {
            int p = 0, q = 0;
            while(p < s.size())
            {
                if(s[p] == d[i][q])
                {
                    p++;
                    q++;
                }
                else
                    p++;
                if(q == d[i].size())
                {
                    return d[i];
                }
            }
        }
        return string("");
    }
};

解题思路2:
由于对字符串数组d进行排序需要一定的时间花销,若省去这个步骤,我们可以直接将每个d中的字符串d[i]与字符串s进行比较。设置记录当前最长的符合返回条件的字符串max_str,如果d[i]比max_str长或者与其等长且字典序更小,则用d[i]更新max_str。时间复杂度为O(n*x),其中n为d中元素的数量,x为字符串s的平均长度。

代码:

class Solution {
public:
    string findLongestWord(string s, vector<string>& d) {
        string max_str = "";
        for(int i = 0; i < d.size(); i++)
        {
            int p = 0, q = 0;
            while(p < s.size())
            {
                if(s[p] == d[i][q])
                {
                    p++;
                    q++;
                }
                else
                    p++;
                if(q == d[i].size())
                {
                    if(d[i].size() > max_str.size() || (d[i].size() == max_str.size() && d[i].compare(max_str) < 0))
                        max_str = d[i];
                }
            }
        }
        return max_str;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值