[Leetcode] #97 Interleaving String

Discription

Given s1s2s3, 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.

Solution

bool isInterleave(string s1, string s2, string s3) {
	int len1 = s1.size(), len2 = s2.size();
	if (len1 + len2 != s3.size())
		return false;
	vector<vector<bool>> dp(len1 + 1, vector<bool>(len2 + 1, false));
	dp[0][0] = true;
	for (int i = 1; i <= len1; i++){
		dp[i][0] = dp[i - 1][0] && (s1[i - 1] == s3[i - 1]);
	}
	for (int j = 1; j <= len2; j++){
		dp[0][j] = dp[0][j - 1] && (s2[j - 1] == s3[j - 1]);
	}
	for (int i = 1; i <= len1; i++){
		for (int j = 1; j <= len2; j++){
			dp[i][j] = (dp[i][j - 1] && s2[j - 1] == s3[i + j - 1]) || (dp[i - 1][j] && s1[i - 1] == s3[i + j - 1]);
		}
	}
	return dp[len1][len2];
}
GitHub-Leetcode:https://github.com/wenwu313/LeetCode

發佈了129 篇原創文章 · 獲贊 52 · 訪問量 19萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章