392. 判断子序列
115. 不同的子序列
- 判断子序列
class Solution {// public boolean isSubsequence(String s, String t) {// int spointer = 0;// int tpointer = 0;// while(spointer < s.length() && tpointer < t.length()){// if(s.charAt(spointer) == t.charAt(tpointer)){// spointer ++;// }// tpointer ++;// }// return spointer == s.length();// }public boolean isSubsequence(String s, String t) {//dp[i][j] 表示以下标i-1为结尾的字符串s,和以下标j-1为结尾的字符串t,相同子序列的长度为dp[i][j]。int length_s = s.length();int length_t = t.length();int[][] dp = new int[length_s+1][length_t+1];for(int i = 1;i<=length_s;i++){char char1 = s.charAt(i-1);for(int j =1;j<=t.length();j++){char char2 = t.charAt(j-1);if(char1 == char2){dp[i][j] = dp[i-1][j-1] + 1;}else{dp[i][j] = dp[i][j-1];}}}if(dp[length_s][length_t] == length_s) return true;return false;}
}
- 不同的子序列
class Solution {public int numDistinct(String s, String t) {//dp[i][j] 以i-1为结尾的s子序列中出现以j-1为结尾的t的个数为dp[i][j]/**//两者末尾相同,则去掉末尾元素,不影响结果s.charAt(i-1) == t.charAt(j-1)//考虑使用s[i-1]和不使用s[i-1]dp[i][j] = dp[i-1][j-1] + dp[i-1][j]s.charAt(i-1) != t.charAt(j-1)dp[i][j] = dp[i-1][j];*/int[][] dp = new int[s.length() + 1][t.length() + 1];for(int i = 0;i<=t.length();i++) dp[0][i] = 0;for(int i = 0;i<=s.length();i++) dp[i][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()];}
}