最长公共子序列算法

/**
  * Created by fhqplzj on 17-2-28 at 上午9:56.
  */
object LongestCommonSubsequence {
  def LCS(s1: String, s2: String): (Int, String) = {
    val m = s1.length
    val n = s2.length
    val dp = Array.ofDim[Int](m + 1, n + 1)
    for (i <- 1 to m; j <- 1 to n) {
      dp(i)(j) = if (s1.charAt(i - 1) == s2.charAt(j - 1)) dp(i - 1)(j - 1) + 1 else math.max(dp(i - 1)(j), dp(i)(j - 1))
    }
    var p1 = m
    var p2 = n
    val stringBuilder = new StringBuilder
    while (p1 > 0 && p2 > 0) {
      if (s1.charAt(p1 - 1) == s2.charAt(p2 - 1)) {
        stringBuilder += s1.charAt(p1 - 1)
        p1 -= 1
        p2 -= 1
      } else if (dp(p1 - 1)(p2) > dp(p1)(p2 - 1)) {
        p1 -= 1
      } else {
        p2 -= 1
      }
    }
    (dp(m)(n), stringBuilder.reverse.toString())
  }

  def main(args: Array[String]): Unit = {
    val s1 = "高新技术开发区北环海路128号"
    val s2 = "高技区北环海路128号"
    println(LCS(s1, s2))
  }
}

你可能感兴趣的:(最长公共子序列算法)