LeetCode刷题 Day55
392. Is Subsequence
Given two strings s and t, return true if s is a subsequence of t , or false otherwise.
A 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).
Example 1:
Input: s = "abc", t = "ahbgdc"
Output: true
Example 2:
Input: s = "axc", t = "ahbgdc"
Output: false
步骤:
- dp[i][j] 含义: 代表该位置子序列长度
- 递推公式: dp[i][j] = dp[i - 1][j - 1] + 1
- 初始化: dp[0][0] = 0
- 遍历顺序: 从左上到右下
- 举例:
代码:
var isSubsequence = function(s, t) {
let dp = Array(s.length + 1).fill(0).map(() => Array(t.length + 1).fill(0));
for (let i = 1; i <= s.length; i++) {
for (let j = 1; j <= t.length; j++) {
if (s[i - 1] === t[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;
};
时间复杂度: O(m * n) 空间复杂度: O(m * n);
115. Distinct Subsequences
Given two strings s and t, return the number of distinct
subsequences
of s which equals t.
The test cases are generated so that the answer fits on a 32-bit signed integer.
Example 1:
Input: s = "rabbbit", t = "rabbit"
Output: 3
Explanation:
As shown below, there are 3 ways you can generate "rabbit" from s.
rabbbit
rabbbit
rabbbit
Example 2:
Input: s = "babgbag", t = "bag"
Output: 5
Explanation:
As shown below, there are 5 ways you can generate "bag" from s.
babgbag
babgbag
babgbag
babgbag
babgbag
代码:
var numDistinct = function(s, t) {
let dp = Array.from(Array(s.length + 1), () => Array(t.length +1).fill(0));
for(let i = 0; i <=s.length; i++) {
dp[i][0] = 1;
}
for(let i = 1; i <= s.length; i++) {
for(let j = 1; j<= t.length; j++) {
if(s[i-1] === t[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];
};
时间复杂度: O(mn) 空间复杂度: O(mn)