Algorithm-week16

Week16

Problem--Medium--392. Is Subsequence

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 tt 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.

题目解析:

这道题目可以用动态规划算法进行求解,首先,我们需要将问题划分出其子问题,也就是前状态是什么,我们求解两段不同长度m,n字符串是否为子串关系,其前状态可以分为求解长度为m-1,n-1的字符串是否为子串关系。所以我们可以直观定义dp[i][j]为长度为i,j的字符串是否为子串关系,这个关系不是单纯的真假关系,而是两者最长的公共子字符串的长度,这样我们在最后只需判断dp[m][n]是否等于s的长度即可。优化后,状态数组可以变为一维数组。

定义状态:

dp[i][j]为长度为i的字符串s与长度为j的字符串t最长公共子字符串长度。

状态转移:

if (s[i - 1] == t[j - 1]): dp[i][j] = dp[i - 1][j - 1] + 1;

else: dp[i][j] = max(dp[i][j - 1], dp[i - 1][j])

优化后:

状态变量可变为dp[i],因为每次更新之后只会用到上一次更新的值,没必要保留所有i更新的值,所以我们保存一次更新值即可,在下次更新中用自己的旧值进行更新。

代码:

class Solution {
public:
    bool isSubsequence(string s, string t) {
        vector<int> dp(t.length() + 1, 0);
        for (int i = 1; i <= s.length(); i++) {
            for (int j = 1; j <= t.length(); j++) {
                if (s[i - 1] == t[j - 1]) {
                    dp[j] = min(dp[j - 1] + 1, i);
                    //cout << s[i - 1] << " " << dp[j] << endl;
                } else {
                    dp[j] = max(dp[j - 1], dp[j]);
                }
                //cout << dp[j] << endl;
            }
        }
        if (dp[t.length()] == s.length()) {
            return true;
        } else {
            return false;
        }
    }
};

简单方法:

其实这道题根本不需要用动态规划来做,LeetCode上分类是动态规划所以引导别人用动态规划做。最简单的方法其实只需遍历t字符串,遇到与s相同字符的s的指针前进一,最后判断s的指针是否直到字符串尾即可。

代码:

class Solution {
public:
    bool isSubsequence(string s, string t) {
        int pos = 0;
        for (int i = 0; i < t.length(); i++) {
            if (t[i] == s[pos]) {
                pos++;
            }
        }
        return pos == s.length();
    }
};




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值