LeetCode_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.

遞歸解法:超時

class Solution {
public:
    
        bool isInterleave(string s1, string s2, string s3) 
        { 
            if (s1.length() + s2.length() != s3.length())
                return false;
                
            return isInterleaveDFS(s1, s2, s3, 0, 0, 0);
        }
            
        bool isInterleaveDFS(string &s1, string &s2, string &s3, int p1, int p2, int p3)
        {
            if (p3 == s3.length())
            {
                return true;
            }
            if (p1 < s1.length() && s1[p1] == s3[p3])
            {
                if (isInterleaveDFS(s1, s2, s3, p1 + 1, p2, p3 + 1))
                {
                    return true;
                }
            }
            if (p2 < s2.length() && s2[p2] == s3[p3])
            {
                if (isInterleaveDFS(s1, s2, s3, p1, p2 + 1, p3 + 1))
                {
                    return true;
                }
            }
            return false;
        }
};

DP解法:

bool isInterleave2(string s1, string s2, string s3)
{
	int len1 = s1.length();
	int len2 = s2.length();
	int len3 = s3.length();
	if (len1 + len2 != len3)
		return false;
	bool f[256][256];
	memset(f, 0, sizeof(bool) * 256 * 256);
	if (s1[0] == s3[0])
	{
		f[1][0] = true;
	}
	else
	{
		f[1][0] = false;
	}
	for (int i = 2; i <= len1; ++i)
	{
		if (f[i-1][0] && (s1[i-1] == s3[i-1]))
		{
			f[i][0] = true;
		}
		else
		{
			f[i][0] = false;
		}
	}
	if (s2[0] == s3[0])
	{
		f[0][1] = true;
	}
	else
	{
		f[0][1] = false;
	}
	for (int i = 2; i <= len2; ++i)
	{
		if (f[0][i-1] && (s2[i-1] == s3[i-1]))
		{
			f[0][i] = true;
		}
		else
		{
			f[0][i] = false;
		}
	}
	for (int i = 1; i <= len1; ++i)
	{
		for (int j = 1; j <= len2; ++j)
		{
			f[i][j] = false;
			if (f[i-1][j] == true && s1[i-1] == s3[i+j-1])
			{
				f[i][j] = true;
			}
			if (f[i][j-1] == true && s2[j-1] == s3[i+j-1])
			{
				f[i][j] = true;
			}
		}
	}
	return f[len1][len2];
}



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