Thursday, January 8, 2015

LeetCode 72: Edit Distance

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 {
    public int minDistance(String word1, String word2) {
        // DP Problem
        // Suppose the length of word1 is i; the length of word2 is j; d[i][j] represents the edit distance
        // If we add x to word1 and add y to word2, the new distance should be d[i+1][j+1]
        // If x == y, d[i+1][j+1] = d[i][j];
        // If x != y, if we insert y to word1 can make word1 == word2, then d[i+1][j+1] = d[i+1][j] + 1;
        // If x != y, if we delete x to word1 can make word1 == word2, then d[i+1][j+1] = d[i][j+1] + 1;
        // If x != y, if we replace x and y can make word1 == word2, then d[i+1][j+1] = d[i][j] + 1.
        // The edit distance is the minimum distance of them.
        int len1 = word1.length();
    	int len2 = word2.length();
     
    	// len1+1, len2+1, because finally return dp[len1][len2]
    	int[][] dp = new int[len1 + 1][len2 + 1];
     
        // Insert i characters to word2 or delete i characters from word1
    	for (int i = 0; i <= len1; i++)
    	    dp[i][0] = i;
     
        // Insert j characters to word1 or delete j characters from word2
    	for (int j = 0; j <= len2; j++)
    		dp[0][j] = j;
     
    	// Iterate though, and check last char
    	for (int i = 0; i < len1; i++)
    	{
    		char c1 = word1.charAt(i);
    		
    		for (int j = 0; j < len2; j++)
    		{
    			char c2 = word2.charAt(j);
     
    			//If last two chars equal
    			if (c1 == c2)
    			    //Update dp value for +1 length
    				dp[i + 1][j + 1] = dp[i][j];
    			else
    			{
    				int replace = dp[i][j] + 1;
    				int insert = dp[i][j + 1] + 1;
    				int delete = dp[i + 1][j] + 1;
     
                    // The edit distance is the minimum distance of them.
    				int min = Math.min(replace, insert);
    				min = Math.min(min, delete);
    				dp[i + 1][j + 1] = min;
    			}
    		}
    	}
     
    	return dp[len1][len2];
    }
}

No comments:

Post a Comment