Hard-题目33:97. Interleaving String

转载 2016年05月31日 23:44:12

题目原文:
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.
题目大意:
给出三个字符串s1,s2,s3,判断s3是不是s1和s2交错组合而成。
题目分析:
很明显这个问题可以缩减为下面的子问题:s1的前i个字符与s2的前j个字符能否交错构成s3的前i+j个字符。那么就用DP来做。
设dp(i,j)表示s1的前i个字符与s2的前j个字符能否交错构成s3的前i+j个字符。那么转移关系如下:

dp(I,j)=(dp(i-1,j)&&s1[i-1]==s3[i+j-1])||(dp(I,j-1)&&s2[j-1]==s3[i+j-1])

很好理解,如果dp(i-1,j)==true,则只需要看s3的第i+j个字符和s1的第i个字符是否一样,dp(I,j-1)==true的情况也同理。时间复杂度仅为O(s1.length*s2.length).
源码:(language:cpp)

class Solution {
public:
    bool isInterleave(string s1, string s2, string s3) {
        int m = s1.size();
        int n = s2.size();
        if(m+n != s3.size())
            return false;
        vector<vector<bool> > path(m+1, vector<bool>(n+1, false));
        for(int i = 0; i < m+1; i ++)
        {
            for(int j = 0; j < n+1; j ++)
            {
                if(i == 0 && j == 0)
                // start
                    path[i][j] = true;
                else if(i == 0)
                    path[i][j] = path[i][j-1] & (s2[j-1]==s3[j-1]);
                else if(j == 0)
                    path[i][j] = path[i-1][j] & (s1[i-1]==s3[i-1]);
                else
                    path[i][j] = (path[i][j-1] & (s2[j-1]==s3[i+j-1])) || (path[i-1][j] & (s1[i-1]==s3[i+j-1]));
            }
        }
        return path[m][n];
    }
};

成绩:
12ms,8.48%,8ms,28.70%

相关文章推荐

Leetcode 97. Interleaving String

97. Interleaving String Total Accepted: 49560 Total Submissions: 219537 Difficulty: Hard ...

[leetcode]97. Interleaving String(Java)

https://leetcode.com/problems/interleaving-string/#/description Given s1, s2, s3, find wh...

LeetCode 97 — Interleaving String (C++ Python)

题目:https://oj.leetcode.com/problems/interleaving-string/ Given s1, s2, s3, find whether s3 is form...

[LeetCode] 97. Interleaving String

LeetCode 动态规划

LeetCode 97. Interleaving String

1. 题目描述 Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. For examp...

LeetCode(97) Interleaving String解题报告

Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.For example, Given: s...

97 - Interleaving String

Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. For example, Given: s...

leetcode 97. Interleaving String(字符串交错出现) DFS深度优先遍历+DP

Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.For example, Given: s...

leetcode: 97. Interleaving String 递归与DP两种算法

Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. For example, Given: s...

LeetCode 97 Interleaving String

Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. For example, Given: ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Hard-题目33:97. Interleaving String
举报原因:
原因补充:

(最多只允许输入30个字)