algorithm

编辑距离

2017-11-26  本文已影响0人  satyrs_sh
static int editDist(String str1 , String str2 , int m ,int n){

    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),    // Insert
                     editDist(str1,  str2, m-1, n),   // Remove
                     editDist(str1,  str2, m-1, n-1) // Replace                     
                   ); //三个子问题
    }
//s: beforeediting,length=n  t: afterediting,length=m
//d: recording the distance
        d = new int[n + 1][m + 1];  
              
        for (i = 0; i <= n; i++) {  
            d[i][0] = i;  
        }  
        for (j = 0; j <= m; j++) {  
            d[0][j] = j;  
        }  
          
         
        for (i = 1; i <= n; i++) {  
            s_i = s.charAt(i - 1);  
              
            for (j = 1; j <= m; j++) {  
                t_j = t.charAt(j - 1);  
                 
                cost = (s_i == t_j) ? 0 : 1;  
                 
                d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1,  
                        d[i - 1][j - 1] + cost);  
            }  
        }  
if x == y, then d[i][j] == d[i-1][j-1]
if x != y, 插入y则 d[i][j] = d[i][j-1] + 1
if x != y, 删除x则 d[i][j] = d[i-1][j] + 1
if x != y, x改变为y则 d[i][j] = d[i-1][j-1] + 1
When x!=y, d[i][j] 取三中编辑方式最小代价。
初始化条件 : d[i][0] = i, d[0][j] = j
上一篇 下一篇

猜你喜欢

热点阅读