Leetcode Interleaving String

来源:互联网 发布:浙江外商直接投资数据 编辑:程序博客网 时间:2024/05/16 17:20

题目和算法描述见http://yufeizhaome.wordpress.com/2014/08/19/leetcode-interleaving-string/

递归的算法在两个string相同元素很多的情况下会超时,因为每种可能性都需要走到“底”才能判断,很多“枝”都被重复判断了很多次。

这里采用动态规划的做法,上述链接中的代码已经非常清晰,不再赘述。

#include <iostream>#include <vector>using namespace std;class Solution {public:bool isInterleave(string s1, string s2, string s3) {int l1 = s1.size();int l2 = s2.size();int l3 = s3.size();if (l1 + l2 != l3){return false;}std::vector<std::vector<bool> > canInterleave(l1 + 1, std::vector<bool>(l2 + 1, false));canInterleave[0][0] = true;for (int i = 1; i <= l1; ++i){canInterleave[i][0] = canInterleave[i - 1][0] && s1[i - 1] == s3[i - 1];}for (int i = 1; i <= l2; ++i){canInterleave[0][i] = canInterleave[0][i - 1] && s2[i - 1] == s3[i - 1];}for (int i = 1; i <= l1; ++i){for (int j = 1; j <= l2; ++j){canInterleave[i][j] = (canInterleave[i - 1][j] && s1[i - 1] == s3[i + j - 1]) || (canInterleave[i][j - 1] && s2[j - 1] == s3[i + j - 1]);}}return canInterleave[l1][l2];}};int main(){Solution s;string s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac", s4 = "aadbbbaccc";cout<<s.isInterleave(s1, s2, s3)<<endl; // 1cout<<s.isInterleave(s1, s2, s4)<<endl; // 0return 0;}


0 0
原创粉丝点击