Leetcode: Interleaving String
来源:互联网 发布:太极软件 政务 编辑:程序博客网 时间:2024/05/16 23:43
Question
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
For example,
Given:
s1 = “aabcc”,
s2 = “dbbca”,
When s3 = “aadbbcbcac”, return true.
When s3 = “aadbbbaccc”, return false.
Show Tags
The first try
class Solution(object): def isInterleave(self, s1, s2, s3): """ :type s1: str :type s2: str :type s3: str :rtype: bool """ if len(s3)!=(len(s1)+len(s2)): return False if len(s1)==0: return True if s2==s3 else False if len(s2)==0: return True if s1==s3 else False i, j, k = 0, 0, 0 while i<len(s1) and j<len(s2): if s3[k]==s1[i]: i += 1 elif s3[k]==s2[j]: j += 1 else: return False k += 1 return True
Wrong case
Input: "aa", "ab", "abaa"Output: falseExpected: true
Solution
Get idea from here.
To solve the problem in last section, a res list is created to record whether the first i elems of s1 and the first elems of s2 ( res[i][j] ) could interleave s3. It also optimized to a one dimension list.
Code
class Solution(object): def isInterleave(self, s1, s2, s3): """ :type s1: str :type s2: str :type s3: str :rtype: bool """ if len(s3)!=(len(s1)+len(s2)): return False mins = s1 if len(s1)<=len(s2) else s2 maxs = s1 if len(s1)>len(s2) else s2 res = [False]*(len(mins)+1) res[0] = True for ind in range(len(mins)): res[ind+1] = res[ind] and mins[ind]==s3[ind] for hind in range(len(maxs)): res[0] = res[0] and maxs[hind]==s3[hind] for vind in range(len(mins)): res[vind+1] = (res[vind+1] and maxs[hind]==s3[hind+vind+1]) or (res[vind] and mins[vind]==s3[hind+vind+1]) return res[-1]
0 0
- LeetCode: Interleaving String
- LeetCode Interleaving String
- LeetCode: Interleaving String
- [Leetcode] Interleaving String
- [LeetCode] Interleaving String
- leetcode 68: Interleaving String
- [Leetcode] Interleaving String
- LeetCode - Interleaving String
- [LeetCode]Interleaving String
- LeetCode: Interleaving String
- Leetcode: Interleaving String
- [Leetcode]Interleaving String
- Leetcode: Interleaving String
- LeetCode:Interleaving String
- LeetCode-Interleaving String
- [leetcode] Interleaving String@DP
- LeetCode:Interleaving String
- LeetCode - Interleaving String
- Html动态添加/删除控件
- makefile 中 $@ $^ %< 使用
- hdu 5056
- No 'Access-Control-Allow-Origin' header is present on the requested resource 的解决方法
- 《Hadoop基础教程》之初识Hadoop
- Leetcode: Interleaving String
- 图片验证码
- 小议:SharePoint Content Database Status: Read Only与Offline
- unity3d5.1物体椭圆旋转选择界面实现(二)
- php二维数组排序方法(array_multisort usort)
- 谷歌开源项目Chromium的源码获取与项目构建(Win7+vs10/vs13)
- Jquery 获取 radio选中值
- 最长回文子串Manacher算法
- cocos2d-x学习笔记(1)