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]。
- 为什么表示下标i-1为结尾的字符串?
是为了方便初始化和处理i-1为负的情况,-1就代表了空字符串。 - 分为两种情况:相等则 相同子序列长度加一,不等 则删除当前元素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]相等
- 用最后一个相等的元素s[i - 1]来匹配,个数为dp[i - 1][j - 1]
- 不用最后一个相等元素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()];
}
}