LeetCode115.不同的子序列
public static int MOD = 1000000007;
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 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])%MOD;
}else {
dp[i][j]=dp[i-1][j];
}
}
}
return dp[s.length()][t.length()];
}
LeetCode583. 两个字符串的删除操作
public int minDistance(String word1, String word2) {
int[][] dp= new int[word1.length()+1][word2.length()+1];
for(int i=1;i<=word1.length();i++) {
dp[i][0]=i;
}
for(int i=1;i<=word2.length();i++) {
dp[0][i]=i;
}
for(int i=1;i<=word1.length();i++) {
for(int j=1;j<=word2.length();j++) {
if(word1.charAt(i-1)==word2.charAt(j-1)) {
dp[i][j]=dp[i-1][j-1];
}else {
dp[i][j]=Math.min(dp[i-1][j-1]+2, Math.min(dp[i-1][j]+1, dp[i][j-1]+1));
}
}
}
return dp[word1.length()][word2.length()];
}
LeetCode72. 编辑距离
public int minDistance(String word1, String word2) {
int[][] dp= new int[word1.length()+1][word2.length()+1];
for(int i=1;i<=word1.length();i++) {
dp[i][0]=i;
}
for(int i=1;i<=word2.length();i++) {
dp[0][i]=i;
}
for(int i=1;i<=word1.length();i++) {
for(int j=1;j<=word2.length();j++) {
if(word1.charAt(i-1)==word2.charAt(j-1)) {
dp[i][j]=dp[i-1][j-1];
}else {
dp[i][j]=Math.min(dp[i-1][j-1]+1, Math.min(dp[i-1][j]+1, dp[i][j-1]+1));
}
}
}
return dp[word1.length()][word2.length()];
}