Edit distance(二维动态规划题目)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_28350997/article/details/82811186

题目1 Edit Distance

传统动态规划问题,两个字符串不一样,对第一个字符每一个位置可以进行删除,修改或者增加,将第一个字符串改成第二个字符串,求最小的操作数
a) Insert a character
b) Delete a character
c) Replace a character

第一字符串长度为m, 长度为n;
方法:
可见要求DP[i+1][j+1],必须要知道二维矩阵中左上,上方和下方的3个值。所以当我们确定第0行和第0列的值后,就可以从上到下、从左到右的计算了。
a) 插入一个字符:word1[0:i] -> word2[0:j-1],然后在word1[0:i]后插入word2[j]
DP[i+1][j+1] = DP[i+1][j]+1
b) 删除一个字符:word1[0:i-1] -> word2[0:j],然后删除word1[i]
DP[i+1][j+1] = DP[i][j+1]+1 删除一个S当前的字符串 ,所以i减少一个,
c)替换一个字符:
word1[i] != word2[j]时,word1[i] -> word2[j]:DP[i+1][j+1] = DP[i][j] + 1

  • Created by liuxiongcheng on 2017/4/10.
    */
    public class Editdistance {

static int min(int x,int y,int z)
{
if(x<y&&x<z)
return x;
else if(y<x&&y<z)
return y;
else
return x;
}
//递归函数解决
static int editDist(String str1,String str2,int m,int n)/把第一个字符串变成第二字符串/ {
if (m == 0) return n;
if (n == 0) return m;
if (str1.charAt(m - 1) == str2.charAt(n - 1))
return editDist(str1, str2, m - 1, n - 1);
/无论如何都要操作一次,三种操作中选出最小的数字,分别对应插入,替换,删除/
return 1 + min(editDist(str1, str2, m, n - 1), editDist(str1, str2, m - 1, n - 1), editDist(str1, str2, m - 1, n));

 }
 //采用动态规划的思想解决
 static  int editDsitDP(String str1,String str2,int m,int n)
 {
     int dp[][]=new int [m+1][n+1];
     for(int i=0;i<=m;i++)
     {
         for(int j=0;j<=n;j++)
         {
             if(i==0)
             {
                 dp[i][j]=j;
             }
           else  if (j==0)
             {
                 dp[i][j]=i;
             }
           else  if(str1.charAt(i-1)==str2.charAt(j-1))
           //相同元素,不用做任何修改,直接等于前面对角处的元素,
                 dp[i][j]=dp[i-1][j-1];
             else
             //  在元素中   下面三种情况分别对应 周边四种情况,在
                 dp[i][j]=1+ min (dp[i-1][j],dp[i][j-1],dp[i-1][j-1]);
                 dp[i][j] = 1+dp[i-1][j-1]  ----代表 替换,
                 dp[i][]

         }
     }
     return dp[m][n];
 }
 public static void main(String[] args) {
    String a="saturday";
    String b="sunday";
    int m=a.length();
    int n=b.length();
    System.out.println(editDist(b,a,n,m));
}

}

# 题目二392. Is Subsequence

从背后进行修改,判断

Example 1:
s = "abc", t = "ahbgdc"

Return true.

Example 2:
s = "axc", t = "ahbgdc"

Return false.
判断s 是否是t的一个子字符串即可

class Solution {
public boolean isSubsequence(String s, String t) {
int m = s.length(), n = t.length();
//n是否为空 true,
if(m==0) return true;
int i=m-1,j=n-1;
while(i>=0 && j>=0){
//两种同时满足情况
if(s.charAt(i)t.charAt(j)){
–i;
–j;
}
//让i回退
else
{
–j;
}
}
// 判断能否处理完所有的元素,
if(i
-1)
return true;
return false;
}
}


猜你喜欢

转载自blog.csdn.net/qq_28350997/article/details/82811186