97. Interleaving String
2017-06-29 14:56
281 查看
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
For example,
Given:
s1 =
s2 =
When s3 =
When s3 =
class Solution(object):
def isInterleave(self, s1, s2, s3):
"""
:type s1: str
:type s2: str
:type s3: str
:rtype: bool
"""
if len(s1) + len(s2) != len(s3):
return False
m = [[False for _ in xrange(len(s1) + 1)] for _ in xrange(len(s2) + 1)]
m[0][0] = True
for i in xrange(1, len(s1)+1):
m[0][i] = m[0][i - 1] and (s1[i - 1] == s3[i - 1])
for i in xrange(1, len(s2)+1):
m[i][0] = m[i - 1][0] and (s2[i - 1] == s3[i - 1])
for i in xrange(1, len(s2)+1):
for j in xrange(1, len(s1)+1):
m[i][j] = (m[i][j - 1] and s1[j - 1] == s3[i+j-1]) or (m[i-1][j] and s2[i - 1] == s3[i+j-1])
return m[len(s2)][len(s1)]
For example,
Given:
s1 =
"aabcc",
s2 =
"dbbca",
When s3 =
"aadbbcbcac", return true.
When s3 =
"aadbbbaccc", return false.
class Solution(object):
def isInterleave(self, s1, s2, s3):
"""
:type s1: str
:type s2: str
:type s3: str
:rtype: bool
"""
if len(s1) + len(s2) != len(s3):
return False
m = [[False for _ in xrange(len(s1) + 1)] for _ in xrange(len(s2) + 1)]
m[0][0] = True
for i in xrange(1, len(s1)+1):
m[0][i] = m[0][i - 1] and (s1[i - 1] == s3[i - 1])
for i in xrange(1, len(s2)+1):
m[i][0] = m[i - 1][0] and (s2[i - 1] == s3[i - 1])
for i in xrange(1, len(s2)+1):
for j in xrange(1, len(s1)+1):
m[i][j] = (m[i][j - 1] and s1[j - 1] == s3[i+j-1]) or (m[i-1][j] and s2[i - 1] == s3[i+j-1])
return m[len(s2)][len(s1)]
相关文章推荐
- 97. Interleaving String
- 97. Interleaving String
- 97. Interleaving String
- LeetCode 97 Interleaving String
- 97.Interleaving String
- 97 Interleaving String
- [LeetCode 97] Interleaving String(Python)
- leetcode_question_97 Interleaving String
- leetcode 97: Interleaving String
- 97. Interleaving String
- 97. Interleaving String
- Leetcode 97 Interleaving String
- [leetcode-97]Interleaving String(java)
- 97. Interleaving String
- leetcode_[python/C++]_97_Interleaving String_动态规划
- Leetcode 97, Interleaving String
- 97. Interleaving String
- [leetcode 97]Interleaving String
- LeetCode-97-Interleaving String DP 记忆化搜索
- [leetcode] 97 Interleaving String