2014年5月11日星期日

Dynamic Programming Solution - Edit Distance - Matrix ***

The idea is to implement dynamic programming. There are two ways of programming (commented, and uncommented). First update zero edge cases, and then use left/upper neighbors to find the value versus diagonal neighbor (or + 1 or not). Return the right bottom element.

Notice that the double comment part (comment in comment), when deal with the zero edges.

public class Solution {
    public int minDistance(String word1, String word2) {
        if(word1 == null || word2 == null){
            return 0;
        }
        if(word1.length() == 0 || word2.length() == 0){
            return Math.max(word1.length(), word2.length());
        }
        int[][] process = new int[word1.length()][word2.length()];
        if(word1.charAt(0) != word2.charAt(0)){
            process[0][0] = 1;
        }
        int count = 0;
        for(int i = 1; i < process.length; i++){
            //process[i][0] = process[i - 1][0] + ((word2.charAt(0) != word1.charAt(i)) ? 1 : 0); // This is wrong since like u could appear twice but this count would miss one count in the final
            process[i][0] = process[i - 1][0] + ((word2.charAt(0) != word1.charAt(i) || count++ >  0) ? 1 : 0);
            //process[i][0] = i;
        }
        count = 0;
        for(int j = 1; j < process[0].length; j++){
            //process[0][j] = process[0][j - 1] + ((word1.charAt(0) != word2.charAt(j)) ? 1 : 0); // This is wrong since like u could appear twice but this count would miss one count in the final
            process[0][j] = process[0][j - 1] + ((word1.charAt(0) != word2.charAt(j) || count++ > 0) ? 1 : 0);
            //process[0][j] = j;
        }
       
        for(int i = 1; i < process.length; i++){
            for(int j = 1; j < process[0].length; j++){
                process[i][j] = Math.min(process[i - 1][j] + 1, process[i][j - 1] + 1);
                if(word1.charAt(i) == word2.charAt(j)){
                //if(word1.charAt(i - 1) == word2.charAt(j - 1)){
                    process[i][j] = Math.min(process[i - 1][j - 1], process[i][j]);
                }else{
                    process[i][j] = Math.min(process[i][j], process[i - 1][j - 1] + 1);
                }
            }
        }
        return process[word1.length() - 1][word2.length() - 1];
    }
}

没有评论: