链接:https://leetcode.com/problems/interleaving-string/description/
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
Example 1:
Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac" Output: true
Example 2:
Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc" Output: false
动态规划
class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
if (s1.length() + s2.length() != s3.length()) return false;
vector<vector<bool>> dp(s1.length() + 1, vector<bool>(s2.length() + 1, false));
dp[0][0] = true;
for(int i=1; i<=s1.length(); i++) if (s3.substr(0, i) == s1.substr(0, i)) dp[i][0] = true;
for(int j=1; j<=s2.length(); j++) if (s3.substr(0, j) == s2.substr(0, j)) dp[0][j] = true;
for(int i=0; i<s1.length(); i++) {
for(int j=0; j<s2.length(); j++) {
if (s3[i + j + 1] != s1[i] && s3[i + j + 1] != s2[j]) dp[i + 1][j + 1] = false;
if (s3[i + j + 1] == s1[i]) dp[i + 1][j + 1] = dp[i + 1][j + 1] || dp[i][j + 1];
if (s3[i + j + 1] == s2[j]) dp[i + 1][j + 1] = dp[i + 1][j + 1] || dp[i + 1][j];
}
}
return dp.back().back();
}
};
贪心
Travel s3 to find s1 greedily, if meet s3[k] != s1[i], we try to check whether s3[k] == s2[j], if no, go backward k and i, incease c, set c as the backward steps count.
class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
int i=0,j=0,k=0,c = 0;
while(k < s3.length()) {
if(!c && s3[k] == s1[i]) { i++; k++; continue; }
if(s3[k] == s2[j]) { j++; k++; c = 0; continue; }
--i; --k; c++;
if(k < 0) break;
}
return k == s3.length() && i == s1.length() && j == s2.length();
}
};