算法

作者: 一直想上树的猪 | 来源:发表于2020-06-10 11:10 被阅读0次
    /**
     * @Classname Lenth
     * @Description Lenth
     * @Date 2020/6/10 11:05 上午
     * @Created by tinner
     */
    public class Lenth {
    
        public static int minDistanceWay(String word1, String word2) {
            int lenWord1 = word1.length();
            int lenword2 = word2.length();
            // minDis[i][j]表示长度为i和长度为j的单词之间的最小编辑距离
            int[][] minDis = new int[lenWord1 + 1][lenword2 + 1];
            for (int i = 1; i <= lenWord1; i++) {
                minDis[i][0] = i;
            }
    
            for (int j = 1; j <= lenword2; j++) {
                minDis[0][j] = j;
            }
    
            for (int i = 1; i <= lenWord1; i++) {
                for (int j = 1; j <= lenword2; j++) {
                    if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
                        minDis[i][j] = minDis[i - 1][j - 1];
                    } else {
                        int deleteWord1 = minDis[i - 1][j] + 1;
                        int deleteWord2 = minDis[i][j - 1] + 1;
                        int replaceWord = minDis[i - 1][j - 1] + 1;
                        minDis[i][j] = Math.min(Math.min(deleteWord1, deleteWord2), replaceWord);
                    }
                }
            }
            return minDis[word1.length()][word2.length()];
        }
    
        public static void main(String[] args) {
            System.out.println(minDistanceWay("dog", "cat"));
        }
    }
    
    

    相关文章

      网友评论

          本文标题:算法

          本文链接:https://www.haomeiwen.com/subject/temutktx.html