为什么我们在这里不使用堆栈?交织的字符串leetcode
我知道我们可以在这里使用动态编程,但是我的第一个直觉是使用堆栈,因为S3由S1和S2的子字符串组成,因此我得出的结论是,S1和S2字符的出现顺序在S3中是相同的,而S3是最长的commonsubsubsubsubsubsubsubsubsubsubsiubsemence。 (s1,s3)= s1和最长的commonsubsequence(s2,s3)= s2,这就是为什么我可以比较S3具有堆栈值和流行字符,如果它们相同(我维护了2个堆栈,并以相反顺序按下S1和S2),如果S3交织在一起,两个堆栈必须最终都空,我们可以返回true(我已附加了我的代码,可能是错误的,但这就是我要做的)
我似乎无法想象这种方法会失败的地方,如果有人有任何想法,请分享您的想法,我真的很挣扎 提前致谢 !
bool isInterleave(string s1, string s2, string s3) {
stack<char>a,b;
for(int i=s1.length()-1;i>=0;i--){
a.push(s1[i]);
}
for(int i=s2.length()-1;i>=0;i--){
b.push(s2[i]);
}
int i=0;
while( i<s3.length()){
int flag=0;
while(!a.empty() &&i<s3.length()&& a.top()==s3[i])
{
a.pop();
i++;
flag=1;
}
while(!b.empty()&&i<s3.length()&&b.top()==s3[i]){
b.pop();
i++;
flag=1
}
if(!flag)i++;
}
return (a.empty()&&b.empty()&& i==s3.length()?true:false);
}
I understood that we can use dynamic programming here but my first intuition was to use stack since s3 is made up of substrings of s1 and s2 so i concluded that the order of occurrence of characters of s1 and s2 will be same in s3 that is LongestCommonSubsequence(s1,s3)=s1 and LongestCommonSubsequence(s2,s3)=s2 and thats why I though I could just compare the characters of s3 with stack values and pop characters if they are same (i maintained 2 stacks and pushed s1 and s2 in reverse order ) if s3 is interleaving both stacks must be empty in the end and we can return true (i have attached my code,it could be wrong but thats what i was trying to do)
i cant seem to visualize where this approach would fail, if anyone has any idea please share your thoughts I'm really struggling
thanks in advance !
bool isInterleave(string s1, string s2, string s3) {
stack<char>a,b;
for(int i=s1.length()-1;i>=0;i--){
a.push(s1[i]);
}
for(int i=s2.length()-1;i>=0;i--){
b.push(s2[i]);
}
int i=0;
while( i<s3.length()){
int flag=0;
while(!a.empty() &&i<s3.length()&& a.top()==s3[i])
{
a.pop();
i++;
flag=1;
}
while(!b.empty()&&i<s3.length()&&b.top()==s3[i]){
b.pop();
i++;
flag=1
}
if(!flag)i++;
}
return (a.empty()&&b.empty()&& i==s3.length()?true:false);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论