Share a C# solution for the C# coders.using DP


  • 0
    T

    ...public class Solution {
    public int MinDistance(string word1, string word2) {

            int length1 = word1.Length;
            int length2 = word2.Length;
            if (length1 == 0)
                return length2;
            if (length2 == 0)
                return length1;
            int[,] nums = new int[length1 + 1, length2 + 1];
            for (int i = 0; i <=length1; i++)
            {
                nums[i, 0] = i;
            }
            for (int i = 0; i <=length2 ; i++)
            {
                nums[0, i] = i;
            }
    
            for (int i = 1; i <= length1; i++)
            {
                for (int j = 1; j <=length2; j++)
                {
                    if (word1[i - 1] == word2[j - 1])
                        nums[i, j] = nums[i - 1, j - 1];
                    else
                    {
                        nums[i, j] = Math.Min(Math.Min(nums[i - 1, j], nums[i, j - 1]), nums[i - 1, j - 1]) + 1;
                    }
                }
            }
    
            return nums[length1, length2];
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.