LeetCode 97 Interleaving String(Python詳解及實現)
阿新 • • 發佈:2019-01-25
【題目】
Given s1, s2, s3, find whether s3 is formedby the interleaving of s1 and s2.
For example,
Given:
s1 = "aabcc",
s2 = "dbbca",
When s3 = "aadbbcbcac", returntrue.
When s3 = "aadbbbaccc", returnfalse.
給定三個字串S1,S2,S3,判斷S3是否能夠由S1,S2交錯組合而成。
【思路】
二維動態規劃:
s1 = "aabcc" s2 = "dbbca" s3 = "aadbbcbcac"
s1, s2只有兩個字串,因此可以展平為一個二維地圖,判斷是否能從左上角走到右下角。dp[i][j]就表示s1的前i個和s2的前j個是否和s3的前i+j個匹配成功
標1的匹配成功。
當s1到達第i個元素,s2到達第j個元素:
地圖上往右一步就是s2[ j-1]匹配s3[i+j-1]。
地圖上往下一步就是s1[ i-1]匹配s3[i+j-1]。
【Python實現】
class Solution(object): def isInterleave(self, s1, s2, s3): """ :type s1: str :type s2: str :type s3: str :rtype: bool """ len_s1 = len(s1) len_s2 = len(s2) len_s3 = len(s3) if len_s1 + len_s2 != len_s3: return False dp = [[False for i in range(len_s2 + 1)] for j in range(len_s1 + 1)] for i in range(0,len_s1 + 1): for j in range(0,len_s2 + 1): if i == 0 and j == 0: dp[i][j] = True elif i == 0: dp[i][j] = dp[i][j-1] and (s2[j-1] == s3[j-1]) elif j == 0: dp[i][j] = dp[i-1][j] and (s1[i-1] == s3[i-1]) else: dp[i][j] = (dp[i-1][j] and s1[i-1] == s3 [i + j - 1]) or (dp[i][j-1] and s2[j-1]== s3[i+j-1]) return dp[len_s1][len_s2]