Skip to content

Instantly share code, notes, and snippets.

@adamkorg
Created February 5, 2020 12:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamkorg/a90aaf22791215c44bfffae9f3f4ca6e to your computer and use it in GitHub Desktop.
Save adamkorg/a90aaf22791215c44bfffae9f3f4ca6e to your computer and use it in GitHub Desktop.
Leetcode 97: Interleaving String (iterative dp)
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool isInterleave(string s1, string s2, string s3) {
if (s1.size() + s2.size() != s3.size()) return false;
vector<vector<bool>> dp(s1.size()+1, vector<bool>(s2.size()+1, false));
if (s3.size() == 0) return true;
dp[0][0] = true;
for (int c=1; c<=s2.size(); ++c) {
if (dp[0][c-1] && s2[c-1]==s3[c-1]) dp[0][c] = true;
}
for (int r=1; r<=s1.size(); ++r) {
if (dp[r-1][0] && s1[r-1]==s3[r-1]) dp[r][0] = true;
}
for (int r=1; r<=s1.size(); ++r) {
for (int c=1; c<=s2.size(); ++c) {
if (dp[r][c-1] && s2[c-1]==s3[r+c-1]) dp[r][c]=true;
if (dp[r-1][c] && s1[r-1]==s3[r+c-1]) dp[r][c]=true;
}
}
return dp[s1.size()][s2.size()];
}
int main() {
string s1 = "aabaac";
string s2 = "aadaaeaaf";
string s3 = "aadaaeaabaafaac";
// string s1 = "aabcc";
// string s2 = "dbbca";
// string s3 = "aadbbbaccc"; //"aadbbcbcac";
cout << isInterleave(s1, s2, s3) << "\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment