leetcode之392. Is Subsequence(C++解法 动态规划 贪心 模式匹配)

题目:
Given a string s and a string t, check if s is subsequence of t.

You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100).

A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, “ace” is a subsequence of “abcde” while “aec” is not).

Example 1:
s = “abc”, t = “ahbgdc”

Return true.

Example 2:
s = “axc”, t = “ahbgdc”

Return false.

Follow up:
If there are lots of incoming S, say S1, S2, … , Sk where k >= 1B, and you want to check one by one to see if T has its subsequence. In this scenario, how would you change your code?

*****************************我是一条分割线*******************

class Solution {
public:
    bool isSubsequence(string s, string t) {
        int coun=s.size();
        int posi=-1;
        int i=0;
        char* str = new char[2];
        str[1] = '\0';
        while(i<coun)
        {
            str[0] = s[i];
            size_t pos=t.find_first_of(str,posi+1,1);
            if(pos==string::npos)
            {
                return false;
            }
            posi=pos;
            i++;
        }
        return true;
    }
};

这个是在对上一道题好好消化之后自己完成的哦,而且一次提交AC(accept),开心三秒钟。
下面开始划重点:
1、string上的find操作有很多,这道题目用到的三个参数的意思是(假定三个参数从左到右分别是a,b,c)从字符串t的第b个位置以c为单位逐个匹配*字符串**a,所以第一个参数是字符串类型哦,开始时想破头皮不知道怎么把s[i]当做字符串传进去,在请教了大神之后,char str = new char[2]横空出世(虽然我到现在这个地方还是有点点不太清楚,不过很好的帮我解决了问题)。
2、动态规划的思想上一篇已经总结过了,那这道题上的最优子结构该怎么描述呢?(我试一下)在t串中寻找s串中的第i个字母,找到之后,从找到的位置后面接着寻找s串中的第(i+1)个字母,如果没有找到的话,就证明t串后面的字母中都不存在你要找的s[i]了,终止返回false即可。所以这个地方我认为用到了动态规划的地方就是posi=pos;,起到了记录中间结果的作用,使得查找不必每次都从头开始,而且不会乱啊,是吧! 好开心,好紧张。开心我又做出来了一道题(而且是传说中的模式匹配),紧张的是我要去做下一个喽~~~

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值