您的位置:首页 > 编程语言 > C语言/C++

LeetCode[97]::Interleaving String C++

2015-08-22 23:40 459 查看
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.

class Solution {

public:

    bool isInterleave(string s1, string s2, string s3) {

        int len1 = s1.length();

        int len2 = s2.length();

        int len3 = s3.length();

        if( len1 == 0 && len2 == 0 && len3 == 0){

            return true;

        }

        if(len3 != ( len1 + len2 )){

            return false;

        }

        vector<bool> dp(len2+1);

        for(size_t i = 0; i <= len1; ++i){

            for(size_t j = 0; j <= len2; ++j){

                if(i == 0){

                    if(j == 0){

                        dp[j] = true;

                    }else{

                        dp[j] = (dp[j-1] && (s2[j-1] == s3[i+j-1]));

                    }

                }else{

                    if(j == 0){

                        dp[j] = (dp[j] && (s1[i-1] == s3[i+j-1]));

                    }else{

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

                    }

                }

            }

        }

        return dp[len2];

    }

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: