392 判断子序列
https://leetcode.cn/problems/is-subsequence/
class Solution { //二维DP滚动数组,初始化是难点
public boolean isSubsequence(String s, String t) { // dp[i][j] 由 dp[i][j - 1] || dp[i - 1][j - 1] && char==char
boolean[] pre = new boolean[s.length() + 1];
pre[0] = true; // 省略的是长t的那一维度,短s="", 长t="" true, s> “” pre[j] = false
for (int i = 1; i <= t.length(); i++) {
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;
for (int j = 1; j <= s.length(); j++) {
if (t.charAt(i - 1) == s.charAt(j - 1) && pre[j - 1] || pre[j]) dp[j] = true;
}
pre = dp;
}
return pre[s.length()];
}
}
class Solution { //二维DP
public boolean isSubsequence(String s, String t) {
boolean[][] dp = new boolean[t.length() + 1][s.length() + 1];
for (int i = 0; i <= t.length(); i++) {
for (int j = 0; j <= s.length(); j++) {
if (j == 0) {
dp[i][j] = true; //初始是s为空,都为空
continue;
}
if (i == 0) continue;
if (t.charAt(i - 1) == s.charAt(j - 1) && dp[i - 1][j - 1] || dp[i - 1][j]) dp[i][j] = true;
}
}
return dp[t.length()][s.length()];
}
}
class Solution { //双指针
public boolean isSubsequence(String s, String t) {
int i = 0, j = 0;
while (i < s.length()) {
while (j < t.length() && s.charAt(i) != t.charAt(j)) {
j++;
}
if (j == t.length()) return false;
j++;
i++;
}
return true;
}
}
115 不同的子序列
https://leetcode.cn/problems/distinct-subsequences/
class Solution {
public int numDistinct(String s, String t) {
int[][] dp = new int[s.length() + 1][t.length() + 1];
dp[0][0] = 1;
for (int i = 1; i <= s.length(); i++) {
for (int j = 0; j <= t.length(); j++) {
if (j == 0) {
dp[i][j] = 1;
continue;
}
dp[i][j] = s.charAt(i - 1) == t.charAt(j - 1) ? (dp[i - 1][j - 1] + dp[i - 1][j]) : (dp[i - 1][j]);
}
}
return dp[s.length()][t.length()];
}
}