leetcode-524 最长子序列 C++

该博客主要讨论LeetCode中的第524题,目标是从给定字符串`s`中删除一些字符,使其变成字典中的一个单词。博主分享了解决该问题的C++实现,以及如何找到最长且字典序最小的可能结果。通过示例输入和输出,展示了算法的运行情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

**524. Longest Word in Dictionary through Deleting
Medium

305

165

Favorite
删除 s 中的一些字符,使得它构成字符串列表 d 中的一个字符串,找出能构成的最长字符串。如果有多个相同长度的结果,返回字典序的最小字符串。

Share
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”**

代码

class Solution {
public:
    string findLongestWord(string s, vector<string>& d) {
        string longWord="";//初始化空字符串
        for(int i=0;i<d.size();i++){//遍历vector里的每一个单词
            int L1=longWord.length();//当前包含的单词的长度 题目要求最长字符串单词
            int L2=d[i].size();//单词的长度
           //如果当前最长单词大于当前vector单词‘
           //或者’虽然相等但字典符小,比较下一个单词
             if(L1>L2||(L1==L2&&longWord<=d[i]))
              continue;
            //类似双指针
            int one=0,two=0;
            //比较字符是否相同,如果相同 比较下一个,如果不同,字符串地址加1
            while(one<s.length()&&two<L2){
                if(s[one]==d[i][two])
                    two++;
                one++;   
            }
            //当vector单词相等 赋值给最大单词
            if(two==L2)
                longWord=d[i];
              
        }
        return longWord;
      
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值