标签:
题目描述:
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.
思路分析:设s2的长度为length2,s1的长度为length1。开一个(length2+1)*(length1+1)的bool数组flag。flag[i][j]表示字符串s1+i和字符串s2+j能否构造s3+i+j。首先初始化二维数组的最后一列和最后一行,根据状态转移方程来求得flag[0][0],即得结果。
代码:
class Solution { public: bool isInterleave(string s1,string s2,string s3) { int index1 = 0,index2 = 0,index3 = 0; int length1 = s1.length(); int length2 = s2.length(); int length3 = s3.length(); if((length1 + length2) != length3) return false; if(length1 == 0) return s2 == s3; if(length2 == 0) return s1 == s3; //生成一个(length2+1)*(length1+1)的bool数组 vector<vector<bool>> flag; for(int i = 0;i < (length2 + 1);i++) { vector<bool> temp(length1+1,false); flag.push_back(temp); } //初始化最后一列 for(int i = length2 - 1;i >= 0;i--) { if(s2[i] == s3[length1 + i]) flag[i][length1] = true; else break; } //初始化最后一行 for(int i = length1 - 1;i >= 0;i--) { if(s1[i] == s3[length2 + i]) flag[length2][i] = true; else break; } for(int i = length2 - 1;i >= 0;i--) for(int j = length1 - 1;j >= 0;j--) { if(s1[j] == s3[i + j]) if(flag[i][j+1]) { flag[i][j] = true; continue; } if(s2[i] == s3[i + j]) if(flag[i+1][j]) { flag[i][j] = true; continue; } } return flag[0][0]; } };
标签:
原文地址:http://blog.csdn.net/yao_wust/article/details/45846427