leetcode刷题笔记九十七题 交错字符串
leetcode刷题笔记九十七题 交错字符串
源地址:97. 交错字符串
问题描述:
给定三个字符串 s1, s2, s3, 验证 s3 是否是由 s1 和 s2 交错组成的。
示例 1:
输入:s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
输出:true
示例 2:输入:s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
输出:false
/**
本题类似于二维数组中按指定字母路径到达终点的路径问题,采用动态规划思想解决问题
初始状态:dp(0)(0) = true
转换方程:dp(i)(j) = (dp(i-1)(j) && s1(i-1) == s3(i+j-1))||(dp(i)(j-1) && s2(j-1) == s3(i+j-1))
*/
object Solution {
def isInterleave(s1: String, s2: String, s3: String): Boolean = {
val s1Length = s1.length
val s2Length = s2.length
val s3Length = s3.length
if(s1Length + s2Length != s3Length) return false
val dp = Array.fill(s1Length+1, s2Length+1)(false)
dp(0)(0) = true
for(i <- 0 to s1Length){
for(j <- 0 to s2Length){
val p = i + j - 1
if (i > 0) dp(i)(j) = dp(i)(j) || (dp(i-1)(j) && s1(i-1) == s3(p))
if (j > 0) dp(i)(j) = dp(i)(j) || (dp(i)(j-1) && s2(j-1) == s3(p))
}
}
return dp(s1Length)(s2Length)
}
}