The Second Most Popular Dynamic Programming Problem

How many Edit Distance problems are there? I guess a very high number.. This is the second most popular Dynamic Programming problem out there (guess the #1? Yeah, Fibonacci. By a mile).

Here is another version of the Edit Distance problem: https://leetcode.com/problems/one-edit-distance/

161. One Edit Distance
Medium
Given two strings s and t, determine if they are both one edit distance apart.
Note: 
There are 3 possiblities to satisify one edit distance apart:
  1. Insert a character into s to get t
  2. Delete a character from s to get t
  3. Replace a character of s to get t
Example 1:
Input: s = "ab", t = "acb"
Output: true
Explanation: We can insert 'c' into s to get t.
Example 2:
Input: s = "cab", t = "ad"
Output: false
Explanation: We cannot get t from s by only one step.
Example 3:
Input: s = "1203", t = "1213"
Output: true
Explanation: We can replace '0' with '1' to get t.
Accepted
96,242
Submissions
299,225

This is 100% Edit Distance: build the DP table, and at the very end, just make sure that the last cell in your DP table is equal to... to... yes, 1 (one). Code is below, cheers, ACC.


public class Solution
{
    public bool IsOneEditDistance(string s, string t)
    {
        if (String.IsNullOrEmpty(s) && String.IsNullOrEmpty(t)) return false;
        if (String.IsNullOrEmpty(s)) return t.Length == 1;
        if (String.IsNullOrEmpty(t)) return s.Length == 1;

        int[][] dp = new int[s.Length + 1][];
        for (int i = 0; i < dp.Length; i++) dp[i] = new int[t.Length + 1];

        dp[0][0] = 0;
        for (int i = 1; i < dp.Length; i++) dp[i][0] = i;
        for (int j = 1; j < dp[0].Length; j++) dp[0][j] = j;

        for (int i = 1; i < dp.Length; i++)
        {
            for (int j = 1; j < dp[0].Length; j++)
            {
                if (s[i - 1] == t[j - 1])
                {
                    dp[i][j] = dp[i - 1][j - 1];
                }
                else
                {
                    dp[i][j] = Math.Min(Math.Min(dp[i - 1][j] + 1, dp[i][j - 1] + 1), dp[i - 1][j - 1] + 1);
                }
            }
        }

        return dp[dp.Length - 1][dp[0].Length - 1] == 1;
    }
}

Comments

Post a Comment

Popular posts from this blog

Count Binary Substrings

Count Vowels Permutation: Standard DP

Maximum Number of Balloons