-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterleavingString.py
More file actions
26 lines (24 loc) · 963 Bytes
/
interleavingString.py
File metadata and controls
26 lines (24 loc) · 963 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Source: https://leetcode.com/problems/interleaving-string/
# Author: Miao Zhang
# Date: 2021-01-16
class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
len1 = len(s1)
len2 = len(s2)
len3 = len(s3)
if len1 + len2 != len3:
return False
dp = [[False for _ in range(len2 + 1)] for _ in range(len1 + 1)]
for i in range(len1 + 1):
for j in range(len2 + 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[i + j - 1]
elif j == 0:
dp[i][j] = dp[i - 1][j] and s1[i - 1] == s3[i + j - 1]
else:
dp[i][j] = (dp[i][j - 1] and s2[j - 1] == s3[i + j - 1]) or (dp[i - 1][j] and s1[i - 1] == s3[i + j - 1])
return dp[len1][len2]