[Leetcode] Edit Distance

来源:互联网 发布:淘宝的优惠券是真的吗 编辑:程序博客网 时间:2024/06/05 20:13

Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)

You have the following 3 operations permitted on a word:

a) Insert a character
b) Delete a character

c) Replace a character


public class Solution {    private int min(int a, int b, int c) {        int min = a < b? a : b;        min = min < c? min : c;        return min;    }        public int minDistance(String word1, String word2) {        int m = word1.length();        int n = word2.length();        int[][] result = new int[m + 1][n + 1];        for(int i = 0; i <= m; i++) {            for (int j = 0; j <= n; j++) {                if(i == 0) {                    result[0][j] = j;                }                else if(j == 0) {                    result[i][0] = i;                }                else {                    if(word1.charAt(i-1) == word2.charAt(j-1)) {                        result[i][j] = result[i - 1][ j - 1];                    }                    else {                        result[i][j] = 1 + min(result[i - 1][j - 1], result[i][j-1], result[i-1][j]);                    }                }            }        }        return result[m][n];    }}


0 0