Problem:
Edit Distance (Levenshtein Distance)

Find the edit distance between given two words s1 and s2.

The disntace is the minimum number of single-character edits required to change one word into the other. The edits including the following operations:

insertion: Insert a character at a particular position.

deletion: Delete a character at a particular position.

substitution: Change the character at a particular position to a different character

Input

s1
s2

Two words s1 and s2 are given in the first line and the second line respectively. The words will consist of lower case characters.

Output

Print the edit distance in a line.

Constraints

1 ≤ length of s1 ≤ 1000

1 ≤ length of s2 ≤ 1000

Sample Input 1

acac
acm

Sample Output 1

2

Sample Input 2

icpc
icpc

Sample Output 2

0

Solution in Scala (judge verdict: Accepted)

import scala.io.StdIn.readLine

object Main extends App {

  val str1 = readLine()
  val str2 = readLine()
  println(levenshteinDistance(str1, str2))

  def levenshteinDistance(str1: String, str2: String): Int = {
    val n = str1.length
    val m = str2.length
    val dp = Array.ofDim[Int](m + 1, n + 1)
    for (i <- 0 to m; j <- 0 to n) {
      var cost: Int = 0
      if (i == 0 && j == 0) cost = 0
      else if (i == 0) cost = j
      else if (j == 0) cost = i
      else {
        var substitutionCost = 0
        if (str2.charAt(i-1) != str1.charAt(j-1)) {
          substitutionCost = 1
        }
        substitutionCost = dp(i-1)(j-1) + substitutionCost
        val insertion_cost = dp(i)(j-1) + 1
        val deletion_cost = dp(i-1)(j) + 1
        cost = Math.min(substitutionCost, Math.min(insertion_cost, deletion_cost))
      }
      dp(i)(j) = cost
    }
    dp(m)(n)
  }
}