97. Interleaving String

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.

剛開始打算用遞歸做,結果TLE,索性就採用動態規劃。

dp[i][j]表示在s1中取i個元素,s2中取j個元素,看是否能和s3中i+j個元素匹配得上。

具體操作爲:

d[0][0]=true;

初始化d[i][0],即把s1中的元素全部放在前面比較,初始化d[0][j]同理。

當計算dp[i][j]時,按照狀態轉移方程即可:

dp[i][j] = (dp[i-1][j] && s1[i-1] == s3[i+j-1]) || (dp[i][j-1] && s2[j-1] == s3[i+j-1]);

最後的得到的dp[row][col]就是匹配結果。

可打表進行驗證。

詳細代碼:

class Solution {
public:
    bool isInterleave(string s1, string s2, string s3) {
        int row=s1.length();
	int col=s2.length();
	if(row+col!=s3.length())
		return false;
	vector<vector<bool> > dp(row+1, vector<bool>(col+1, false));
	dp[0][0]=true;
	for (int j = 1; j <=col; j++)
		dp[0][j]=dp[0][j-1]&&(s2[j-1]==s3[j-1]);
	for (int i = 1; i <= row; i++)
		dp[i][0]=dp[i-1][0]&&(s1[i-1]==s3[i-1]);
	for(int i=1;i<=row;i++)
	{
		for (int j = 1; j <=col; j++)
		{
			if((dp[i][j-1]&&s2[j-1]==s3[i+j-1])||(dp[i-1][j]&&s1[i-1]==s3[i+j-1]))
				dp[i][j]=true;
			else
			        dp[i][j]=false;
		}
	}
	return dp[row][col];   
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章