def(self, s1, s2, s3): if len(s1) + len(s2) != len(s3): returnFalse defbackTrack(i, j, visited): if i == len(s1) and j == len(s2): returnTrue state = (i, j) if state in visited: returnFalse k = i + j if i < len(s1) and s1[i] == s3[k] and backTrack(i + 1, j, visited): returnTrue if j < len(s2) and s2[j] == s3[k] and backTrack(i, j + 1, visited): returnTrue visited.add(state); returnFalse visited = set() return backTrack(0, 0, visited)
classSolution: def(self, s1: str, s2: str, s3: str) -> bool: L1, L2, L3 = len(s1), len(s2), len(s3) if L3 != L1 + L2: returnFalse dp = [[Truefor _ in range(L1 + 1)] for _ in range(L2 + 1)] for i in range(1, L2 + 1): dp[i][0] = s2[i - 1] == s3[i - 1] and dp[i - 1][0] for i in range(1, L1 + 1): dp[0][i] = s1[i - 1] == s3[i - 1] and dp[0][i - 1] for i in range(1, L2 + 1): for j in range(1, L1 + 1): dp[i][j] = (s3[i + j - 1] == s1[j - 1] and dp[i][j - 1]) or (s3[i + j - 1] == s2[i - 1] and dp[i - 1][j]) # print(dp[i]) return dp[L2][L1]
优化: 滚动数组
特殊解法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution: def(self, s1: str, s2: str, s3: str) -> bool: """ :type s1: str :type s2: str :type s3: str :rtype: bool """ if len(s1) + len(s2) != len(s3): returnFalse i, j, p = 0, 0, 0# i, j, p are pointers for s1, s2 and s3 while i >= 0and j < len(s2): if i < len(s1) and s3[p] == s1[i]: # always choose the first string i, p = i + 1, p + 1 elif s3[p] == s2[j]: # if the first string doesn't match, we choose the second string j, p = j + 1, p + 1 else: # if choosing the first string was wrong in previous steps, we retro i, j = i - 1, j + 1 return s1[i:] + s2[j:] == s3[p:] and i >= 0
近期评论