Sunday, November 15, 2015

[leetcode] Edit Distance

写code 常有漏写的问题。。要仔细点
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Solution {
    public int minDistance(String word1, String word2) {
        if (word1 == null || word2 == null) return 0;
        if (word1.equals("")) return word2.length();
        if (word2.equals("")) return word1.length();
        
        int oneL = word1.length();
        int twoL = word2.length();
        int[] lookup = new int[oneL+1];
        for (int i = 0; i < oneL+1; i++){
            lookup[i] = i;
        }
        for (int i = 1; i < twoL+1; i++){
            int upLeft = i-1;
            lookup[0] = i;
            for (int j = 1; j < oneL+1; j++){
                int temp = lookup[j];
                lookup[j] = Math.min(lookup[j-1]+1, 
                                     Math.min(lookup[j]+1, upLeft+diff(word1.charAt(j-1), word2.charAt(i-1))));
                upLeft = temp;
            }
        }
        return lookup[oneL];
    }
    
    public int diff(char a, char b){
        return a==b?0:1;
    }
}

No comments:

Post a Comment