【LeetCode】524. Longest Word in Dictionary through Deleting

法一

        遍历 dictionary 数组,取其字符串元素,记为 temp 与字符串 s 进行比较。

class Solution {
public:
    string findLongestWord(string s, vector<string>& dictionary) {
        int max = 0;
        string res;
        for(int i = 0; i < dictionary.size(); ++i) {
            string temp = dictionary[i]; // 存放dictionary数组中第 i + 1 个字符串元素
            // j指向temp中的第一个字符, k指向s中的第一个字符
            int j = 0, k = 0;
            while(j < temp.length() && k < s.length()) {
                if(temp[j] == s[k]) ++j;
                ++k;
            }
            if(j >= temp.length()) { // 若可以通过s得到temp,则 j 大小等于temp的长度
                if(j > max) {
                    max = j;
                    res = temp;
                } else if(j == max && res > temp) {
                    res = temp;
                }
            }
        }
        return res;
    }
};

法二

        使用 lambda 表达式结合 sort() 重新排序 dictionary 数组,使其按照字符串长度由大到小排序,如果长度相等,则按照字符串大小由小到大排序。

class Solution {
public:
    string findLongestWord(string s, vector<string>& dictionary) {
        // 排序 dictionary
        sort(dictionary.begin(), dictionary.end(), [](string a, string b) {
            if(a.length() != b.length()) return a.length() > b.length();
            else return a < b;
        });
        // 从头遍历 dictionary 数组,直到找到第一个满足条件的数组元素为止
        for(int i = 0; i < dictionary.size(); ++i) {
            string temp = dictionary[i];
            int j = 0, k = 0;
            while(j < s.length() && k < temp.length()) {
                if(s[j] == temp[k]) ++k;
                ++j;
            }
            if(k == temp.length()) return temp;
        }
        return "";
    }
};

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值