LeetCode 524. 通过删除字母匹配到字典里最长单词

简介: LeetCode 524. 通过删除字母匹配到字典里最长单词

524. 通过删除字母匹配到字典里最长单词


双指针

对列表里的每一个字母进行匹配测试,如果可以完全匹配,再与已有结果进行对比,找到最优解。

class Solution
{
public:
    string findLongestWord(string s, vector<string> &dictionary)
    {
        string res = "";
        for (auto &&word : dictionary)
        {
            int i = 0, j = 0;
            while (i < word.length() && j < s.length())
            {
                if (word[i] == s[j])
                {
                    i++;
                }
                j++;
            }
            if (i == word.length())
            {
                if (i > res.length() || (i == res.length() && word < res))
                {
                    res = word;
                }
            }
        }
        return res;
    }
};


排序

先将 dictionary 依据字符串长度的降序和字典序的升序进行排序,然后从前向后找到第一个符合条件的字符串直接返回即可。

class Solution
{
public:
    static bool compare(const string &a, const string &b)
    {
        if (a.length() == b.length())
        {
            return a < b;
        }
        else
        {
            return a.length() > b.length();
        }
    }
    string findLongestWord(string s, vector<string> &dictionary)
    {
        sort(dictionary.begin(), dictionary.end(), compare);
        for (auto &&i : dictionary)
        {
            cout << i << endl;
        }
        string res = "";
        for (auto &&word : dictionary)
        {
            int i = 0, j = 0;
            while (i < word.length() && j < s.length())
            {
                if (word[i] == s[j])
                {
                    i++;
                }
                j++;
            }
            if (i == word.length())
            {
                res = word;
                break;
            }
        }
        return res;
    }
};
目录
相关文章
|
4月前
|
Go
golang力扣leetcode 49.字母异位词分组
golang力扣leetcode 49.字母异位词分组
17 0
|
4月前
|
Go
golang力扣leetcode 17.电话号码的字母组合
golang力扣leetcode 17.电话号码的字母组合
23 0
|
4月前
leetcode-917:仅仅反转字母
leetcode-917:仅仅反转字母
28 0
|
4月前
leetcode-1220:统计元音字母序列的数目
leetcode-1220:统计元音字母序列的数目
30 0
|
4月前
|
Go
golang力扣leetcode 438.找到字符串中所有字母异位词
golang力扣leetcode 438.找到字符串中所有字母异位词
22 0
|
4月前
|
算法 测试技术 C#
【单调栈】LeetCode2030:含特定字母的最小子序列
【单调栈】LeetCode2030:含特定字母的最小子序列
|
存储 编译器 Linux
标准库中的string类(中)+仅仅反转字母+字符串中的第一个唯一字符+字符串相加——“C++”“Leetcode每日一题”
标准库中的string类(中)+仅仅反转字母+字符串中的第一个唯一字符+字符串相加——“C++”“Leetcode每日一题”
|
15天前
【力扣】1832.判断句子是否为全字母句
【力扣】1832.判断句子是否为全字母句
|
2月前
leetcode热题100. 字母异位词分组
leetcode热题100. 字母异位词分组
18 0
|
3月前
|
Java
LeetCode-电话号码的字母组合-Java
电话号码的字母组合-Java
14 0

热门文章

最新文章