您的位置:首页 > 其它

LeetCode —— Interleaving String

2013-04-16 21:32 375 查看
链接:http://leetcode.com/onlinejudge#question_97

原题:

Given s1, s2, s3,
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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (s1.size() + s2.size() != s3.size())
return false;
return isInterleave(s1, 0, s2, 0, s3, 0);
}

private:
bool isInterleave(const string &s1, int i1,
const string &s2, int i2, const string &s3, int i3) {

if (i3 == s3.size())
return true;

if (i1 < s1.size() && s1[i1] == s3[i3]) {
if (isInterleave(s1, i1+1, s2, i2, s3, i3+1))
return true;
}

if (i2 < s2.size() && s2[i2] == s3[i3]) {
if (isInterleave(s1, i1, s2, i2+1, s3, i3+1))
return true;
}

return false;
}
};


所以只能开个数组来记录状态

对于S3.size = n,检测能否由x长的S1和y长的S2交叉构成,这里x + y = n

只能由两种方式到达:

1) array[x-1][y] --> array[x][y], if S1[x] == S3


2) array[x][y-1] --> array[x][y], if S2[y] == S3


class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (s1.size() + s2.size() != s3.size())
return false;
vector<vector<bool> > array;
for (int i=0; i<=s1.size(); i++) {
array.push_back(vector<bool>(s2.size()+1, false));
}
array[0][0] = true;
for (int n=1; n<=s3.size(); n++) {
for (int x=0, y=n; x<=n; x++, y--) {
if (x>=0 && x<=s1.size() && y>=0 && y<=s2.size()) {
if ( (x-1 >= 0 && array[x-1][y] && s3[n-1]==s1[x-1]) ||
(y-1 >= 0 && array[x][y-1] && s3[n-1]==s2[y-1]) )
array[x][y] = true;
else
array[x][y] = false;
}
}
}
return array[s1.size()][s2.size()];
}
};


当然在空间上可以优化一下:

class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (s1.size() + s2.size() != s3.size())
return false;

if (s1.size() == 0 || s2.size() == 0) {
if (s1 == s3 || s2 == s3)
return true;
return false;
}

vector<bool> vec(s2.size() + 1);
vector<vector<bool> > state;
state.push_back(vec);
state.push_back(vec);

int cur = 0;
int pre = 1;
state[cur][0] = true;
for (int i=0; i<s2.size(); i++)
if (s2[i] == s3[i])
state[cur][i+1] = true;
else
break;

for (int i=0; i<s1.size(); i++) {
cur = (cur + 1) % 2;
pre = (pre + 1) % 2;
if (state[pre][0] && s1[i] == s3[i])
state[cur][0] = true;
else
state[cur][0] = false;

for (int j=0; j<s2.size(); j++) {
if ((s1[i] == s3[i+j+1] && state[pre][j+1]) || (s2[j] == s3[i+j+1] && state[cur][j]))
state[cur][j+1] = true;
else
state[cur][j+1] = false;
}
}

return state[cur].back();
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: