【LeetCode OJ】Interleaving String

时间:2022-09-01 21:30:14

Problem Link:

http://oj.leetcode.com/problems/interleaving-string/

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.

This problem can solved by using DFS on a binary tree. The tree node has three integers (p1,p2,p3), which denotes that s3[0..p3-1] is the interleaving of s1[0..p1-1] and s2[0..p2-1]. For each node, there are following choices:

  1. If p3 == len(s3), it follows that s3 is the interleaving of s1 and s2 (we need assume that len(s3) = len(s1)+len(s2)), return True
  2. If p1 < len(s1) and s1[p1] == s3[p3], then s3[0..p3] could be the interleaving of s1[0..p1] and s2[0..p2-1], so we can go deeper to the node (p1+1, p2, p3+1);
  3. If p2 < len(s2) and s2[p2] == s3[p3], then s3[0..p3] could be the interleaving of s1[0..p1-1] and s2[0..p2], so we can go deeper to the node (p1, p2+1, p3+1);
  4. Otherwise, we cannot go deeper and this path will be terminated.

If we check all possible paths using DFS, and there is no successful path, we would return False and terminate the program. The python code should be as follows.

class Solution:
# @return a boolean
def isInterleave(self, s1, s2, s3):
n1 = len(s1)
n2 = len(s2)
n3 = len(s3)
if n1 + n2 != n3:
return False
# DFS
q = []
q.append( (0,0,0) ) # checked length for s1, s2, s3
while q:
l1, l2, l3 = q.pop()
# If checked length of s3 equals to length of s3, then return True
if l3 == n3:
return True
# If availabe char in s1:
if l1 < n1 and s1[l1] == s3[l3]:
q.append((l1+1,l2,l3+1))
# If available char in s2:
if l2 < n2 and s2[l2] == s3[l3]:
q.append((l1,l2+1,l3+1))
return False

I used build-in structure list implementing the Queue structure. However, the leetcode judging system returns timeout for this DFS implementation. I think it will be worse if you use recursive function instead of queue to carry out the DFS.

So I have to solve it in a more efficient way, I choose DP. I define a boolean 2D array A[0..n1][0..n2] to denote if s3[0:i+j] is the interleaving of s1[0:i] and s2[0:j]. The recursive formula for this DP solution is:

A[0][0] = True, since "" is the interleaving of "" and ""

A[0][j] = True, if s2[0:j] == s3[0:j], which means s3 is the interleaving of "" and s2 if s2 == s3

A[i][0] = True, if s1[0:i] == s3[0:i], which means s3 is the interleaving of s1 and "" if s1 == s3

A[i][j] = True if 1) A[i-1][j] = True and s1[i-1] == s3[i+j-1]; or 2) A[i][j-1] = True and s2[j-1] == s3[i+j-1], for 0<i<=n1, 0<j<=n2

A[][] is (n1+1)*(n2+1) array where A[i][j] means s3[0:i+j] is the interleaving of s1[0:i] and s2[0:j]. We can fill the A-table in a bottom-up way and just return A[n1][n2] to see if s3 is the interleaving of s1 and s2. The python code is as follows, which accepted by the leetcode OJ system.

class Solution:
# @return a boolean
def isInterleave(self, s1, s2, s3):
# A[i][j] means s1[0:i] and s2[0:j] is interleaves of s3[0:i+j]
# A[0][0] = True, since "" and "" are interleaves of ""
# A[0][j] = True, if s2[0:j] == s3[0:j]
# A[i][0] = True, if s1[0:i] == s3[0:j]
# A[i][j] = True, if any of following is true:
# 1) A[i-1][j] = True and s1[i-1] == s3[i+j-1]
# 2) A[i][j-1] = True and s2[j-1] == s3[i+j-1]
n1 = len(s1)
n2 = len(s2)
n3 = len(s3)
if n1 + n2 != n3:
return False
# Initialization
A = []
for _ in xrange(n1+1):
A.append([False]*(n2+1))
# Boundary conditions
A[0][0] = True
for j in xrange(n2):
if s2[j] == s3[j]:
A[0][j+1] = True
for i in xrange(n1):
if s1[i] == s3[i]:
A[i+1][0] = True
# Fill the table
for x in xrange(n1):
for y in xrange(n2):
i = x+1
j = y+1
if (A[i-1][j] and s1[i-1] == s3[i+j-1]) or (A[i][j-1] and s2[j-1] == s3[i+j-1]):
A[i][j] = True
return A[n1][n2]

【LeetCode OJ】Interleaving String的更多相关文章

  1. 【LeetCode OJ】Reverse Words in a String

    Problem link: http://oj.leetcode.com/problems/reverse-words-in-a-string/ Given an input string, reve ...

  2. 【LeetCode OJ】Distinct Subsequences

    Problem Link: http://oj.leetcode.com/problems/distinct-subsequences/ A classic problem using Dynamic ...

  3. 【LeetCode OJ】Word Ladder II

    Problem Link: http://oj.leetcode.com/problems/word-ladder-ii/ Basically, this problem is same to Wor ...

  4. 【LeetCode OJ】Word Ladder I

    Problem Link: http://oj.leetcode.com/problems/word-ladder/ Two typical techniques are inspected in t ...

  5. 【LeetCode OJ】Palindrome Partitioning II

    Problem Link: http://oj.leetcode.com/problems/palindrome-partitioning-ii/ We solve this problem by u ...

  6. 【LeetCode OJ】Palindrome Partitioning

    Problem Link: http://oj.leetcode.com/problems/palindrome-partitioning/ We solve this problem using D ...

  7. 【LeetCode OJ】Valid Palindrome

    Problem Link: http://oj.leetcode.com/problems/valid-palindrome/ The following two conditions would s ...

  8. 【LeetCode OJ】Word Break II

    Problem link: http://oj.leetcode.com/problems/word-break-ii/ This problem is some extension of the w ...

  9. 【LeetCode OJ】Word Break

    Problem link: http://oj.leetcode.com/problems/word-break/ We solve this problem using Dynamic Progra ...

随机推荐

  1. JMX超详细解读

    一.JMX的定义 JMX(Java Management Extensions)是一个为应用程序植入管理功能的框架.JMX是一套标准的代理和服务,实际上,用户可以在任何Java应用程序中使用这些代理和 ...

  2. 一个关于正整数x的约数个数的结论

    分析理解:x的每一个约数都是由x的若干个质因数的积构成. 再根据乘法原理,每个质因数Pi的选择可以是0~Ni个,所以上述结论成立.

  3. JavaEE通过response实现请求重定向

    请求重定向指的是一个web资源收到客户端请求后,通知客户端去访问另外一个web资源,这称之为请求重定向.302状态码和location头即可实现重定向. 请求重定向最常见的应用场景就是用户登录. 下面 ...

  4. 如何在sourcetree 下提交代码到gerrit上

    gerrit的审核机制决定了提交到远程到代码并非远程master分支,而是/refs/for/master 分支,所以需要解决怎么在sourcetree下提交代码到/refs/for/master分支 ...

  5. JSON和JSONP区别

    JSON(JavaScript Object Notation)和JSONP(JSON with Padding) JSON是一种数据交换格式,JSONP是一种跨域数据交互协议 JSONP利用scri ...

  6. MVC &plus;EF&plus;linq 多表联查

    关于linq的多表联查效果的实现: 后台多表查询  内连接: SELECT [Extent2].[partID] AS [partID], [Extent1].[userName] AS [userN ...

  7. 【源代码】TreeMap源代码剖析

    注:下面源代码基于jdk1.7.0_11 之前介绍了一系列Map集合中的详细实现类,包含HashMap,HashTable,LinkedHashMap.这三个类都是基于哈希表实现的,今天我们介绍还有一 ...

  8. 云计算--网络原理与应用--20171123--网络地址转换NAT

    NAT的概述 NAT的配置 实验 一. NAT的概述 NAT(Network address translation,网络地址转换)通过将内部网络的的私有地址翻译成全球唯一的共有网络IP地址,是内部网 ...

  9. &period;NET Core 必备安全措施

    .NET Core大大简化了.NET应用程序的开发.它的自动配置和启动依赖大大减少了开始一个应用所需的代码和配置量,本文目的是介绍如何创建更安全的.NET Core应用程序. 1.在生产中使用HTTP ...

  10. WPF如何实现TreeView节点重命名

    我们经常看到一些软件比如酷狗音乐,在对列表右键进行重命名的时候,当前列表会泛白并且进入可编辑状态,当我们更改完成后就会并进入非编辑状态,这些具体是怎么实现的呢?下面的方法也许会提供一些思路,下面的Tr ...