All problems

Problem 187

Edit Distance

Hard · 30 pts · String, Dynamic Programming

Problem

You are given two strings S and T. In one operation you can insert a character, delete a character, or replace a character with another one. Find the minimum number of operations needed to turn S into T. This number is called the edit distance (or Levenshtein distance). Let dp[i][j] be the distance between the first i characters of S and the first j characters of T. If the last characters are equal, dp[i][j] = dp[i - 1][j - 1]. Otherwise it is 1 + the minimum of dp[i - 1][j] (delete), dp[i][j - 1] (insert) and dp[i - 1][j - 1] (replace).

Input

Two lines: strings S and T of lowercase letters.

Output

Print the edit distance.

Constraints

1 <= |S|, |T| <= 500

Example input

horse
ros

Example output

3

Explanation

To turn horse into ros: replace h with r (rorse), delete the first r (rose), and delete e (ros). That is 3 operations, and it cannot be done in fewer.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Longest Common Subsequence Next: 0/1 Knapsack