原题:
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.
解题思路:
这个题是个dp,用一个record来记录,首先需要判断一下s1和s2的长度的和与s3的长度是否一致,如果不一致直接返回false
如果一致,则首先判断s1的第index1个或s2的第index2个,是否和s3的index3个元素一样,要和两个字符串都比较,
之后的递归处理处理就行,需要注意的是,这两种情况只要有一个是true,那结果就是true,所以用或运算。
这里还有一个情况,就是dp的时候,s1或s2的index会超过其字符串的长度,为了解决这个问题,我把record的两个维度都增加了一个,当s1的index越界后,不会再增加,因此index1最大值就是s1.length()。当s1,s2,s3都越界后,代表已经匹配完了,而且这几个字符串也没有多出字符,返回true
代码如下(8ms):
class Solution { public: bool isInterleave(string s1, string s2, string s3) { if( (s1.length()+s2.length()) != s3.length()) return false; vector<int>temp(s2.length()+1,-1); vector<vector<int>>record(s1.length()+1,temp); return inter(s1,s2,s3,0,0,0,record); } bool inter(string &s1, string &s2, string &s3,int index1,int index2,int index3,vector<vector<int>>&record){ if(record[index1][index2] != -1) return record[index1][index2]; if(index3>=s3.length()&&index1>=s1.length()&&index2>=s2.length()){ record[index1][index2] = true; return true; } bool result = false; //一定要判断index1和length的比较,否则在取字符时会有错误 if(index1<s1.length()&&s1[index1]==s3[index3]) { result |= inter(s1,s2,s3,index1+1,index2,index3+1,record); } if(index2<s2.length()&&s2[index2]==s3[index3]) { result |= inter(s1,s2,s3,index1,index2+1,index3+1,record); } record[index1][index2] = result; return result; } };