day55|● 392.判断子序列 ● 115.不同的子序列

392.判断子序列

Input: s = “abc”, t = “ahbgdc”
Output: true
subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., “ace” is a subsequence of “abcde” while “aec” is not).

双指针

class Solution {
    public boolean isSubsequence(String s, String t) {
        int i = 0;
        int j = 0;
        while (i < s.length() && j < t.length()) {
            if (s.charAt(i) == t.charAt(j)) {
                i++;
                j++;
            } else{
                j++;
            }
        }
        return (i==s.length());
    }
}

动态规划

dp[i][j] 表示以下标i-1为结尾的字符串s,和以下标j-1为结尾的字符串t,相同子序列的长度为dp[i][j]。

  1. 为什么表示下标i-1为结尾的字符串?
    是为了方便初始化和处理i-1为负的情况,-1就代表了空字符串。
  2. 分为两种情况:相等则 相同子序列长度加一,不等 则删除当前元素t[j - 1]。只能删除t的元素因为s是t的子序列。
    和1143.最长公共子序列相似,但它是两个字符串都可以删元素
class Solution {
    public boolean isSubsequence(String s, String t) {
        int[][] dp = new int[s.length()+1][t.length()+1];
        for (int i = 1; i <= s.length(); i++) {
            for (int j = 1; j <= t.length(); j++) {
                if (s.charAt(i-1) == t.charAt(j-1)) {
                    dp[i][j] = dp[i-1][j-1]+1;
                } else {
                    dp[i][j] = dp[i][j-1];
                }
            }
        }
        return (dp[s.length()][t.length()] == s.length());
    }
}

115.不同的子序列

Given two strings s and t, return the number of distinct subsequences of s which equals t.
Input: s = “rabbbit”, t = “rabbit”
Output: 3
Explanation:
As shown below, there are 3 ways you can generate “rabbit” from s.
rabbbit
rabbbit
rab b bit

dp[i][j]:以i-1为结尾的s子序列中出现以j-1为结尾的t的个数为dp[i][j]。

两种情况:
一、s[i - 1] 与 t[j - 1]相等

  1. 用最后一个相等的元素s[i - 1]来匹配,个数为dp[i - 1][j - 1]
  2. 不用最后一个相等元素s[i - 1]来匹配,相当于删除了最后一个元素,个数为dp[i - 1][j]。s:bagg 和 t:bag

二、s[i - 1] 与 t[j - 1] 不相等
dp[i][j]只有一部分组成,不用s[i - 1]来匹配(就是模拟在s中删除这个元素),只考虑不包含它的子字符串。

class Solution {
    public int numDistinct(String s, String t) {
        int[][] dp = new int[s.length()+1][t.length()+1];
        for(int i=0; i<=s.length();i++){
            dp[i][0] = 1;
        }
        for(int j=1; j<=t.length();j++){
            dp[0][j] = 0;
        }
        dp[0][0] = 1;
        for (int i = 1; i <= s.length(); i++) {
            for (int j = 1; j <= t.length(); j++) {
                if (s.charAt(i-1) == t.charAt(j-1)) {
                    dp[i][j] = dp[i-1][j-1] + dp[i-1][j];
                } else {
                    dp[i][j] = dp[i-1][j];
                }
            }
        }
        return dp[s.length()][t.length()];
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值