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.
给定字符串s1,s2,s3, 判断s3是不是s1和s2中的字交叉组合而成。注意,s1,s2中的字符相对位置在s3中不发生改变
class Solution { public: bool isInterleave(string s1, string s2, string s3) { if(s1.length()+s2.length()!=s3.length())return false; vector<vector<bool> >matrix(s1.length()+1, vector<bool>(s2.length()+1, false)); //初始化matrix[0][0]; matrix[0][0]=true; //初始化第一行 for(int j=1; j<=s2.length(); j++){ matrix[0][j]= matrix[0][j-1]&&s2[j-1]==s3[j-1]; } //初始化第一列 for(int i=1; i<=s1.length(); i++){ matrix[i][0]= matrix[i-1][0]&&s1[i-1]==s3[i-1]; } //初始化其他单元 for(int i=1; i<=s1.length(); i++){ for(int j=1; j<=s2.length(); j++){ matrix[i][j]=(matrix[i-1][j]&&s1[i-1]==s3[i+j-1])||(matrix[i][j-1]&&s2[j-1]==s3[i+j-1]); } } return matrix[s1.length()][s2.length()]; } };
LeetCode: Interleaving String [097],布布扣,bubuko.com
LeetCode: Interleaving String [097]
原文地址:http://blog.csdn.net/harryhuang1990/article/details/28092059