leetcode Interleaving String

来源:互联网 发布:java多线程socket队列 编辑:程序博客网 时间:2024/05/20 03:38

题目

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.

题目来源:https://leetcode.com/problems/interleaving-string/

分析

动态规划。构造二维辅助数组dp[len1+1][len2+1]。
dp[i+1][j+1] == true 表示s1[0…i]和s2[0…j]能够构造成s3[0…i+j+1]。
递推公式:
dp[i+1][j+1] = (dp[i+1][j] && (s3.at(i+j+1) == s2.at(j))) || (dp[i][j+1] && s3.at(i+j+1) == s1.at(i));

代码

class Solution {public:    bool isInterleave(string s1, string s2, string s3) {        int len1 = s1.length();        int len2 = s2.length();        int len3 = s3.length();        if(len3 != len1 + len2)            return false;        vector<vector<bool> > dp(len1 + 1, vector<bool> (len2 + 1, false));        dp[0][0] = true;        for(int i = 0; i < len1; i++)            dp[i+1][0] = (s1.at(i) == s3.at(i)) && dp[i][0];        for(int i = 0; i < len2; i++)            dp[0][i+1] = (s2.at(i) == s3.at(i)) && dp[0][i];        for(int i = 0; i < len1; i++){            for(int j = 0; j < len2; j++){                dp[i+1][j+1] = (dp[i+1][j] && (s3.at(i+j+1) == s2.at(j))) || (dp[i][j+1] && s3.at(i+j+1) == s1.at(i));            }        }        return dp[len1][len2];    }};
0 0
原创粉丝点击