我知道已经对此有一个关于stackoverflow的问题,但是我的代码是不同的。所以我用堆栈来解决这个问题,但是以某种方式我的输出就不能正确输出,但是当我尝试使用给出错误输出的输入测试用例在纸上解决这个问题时,我能够得到正确的答案,我缺少什么代码还是哪里错了?
错误输出的测试用例-))))))()())((())))())((()()()()(((()))())
我的输出-6,预期输出-20
我的代码-
#include <iostream>
#include <string>
#include <stack>
using namespace std;
int main() {
//code
int tc,count,max;
cin>>tc;
while(tc--){
string s;
cin>>s;
max = 0;
count = 0;
stack<char> store;
int len = s.size();
for(int i=0;i<len;i++){
if(s[i] == '(') store.push(s[i]);
else{
if(!store.empty() && store.top() == '('){
count+= 2;
store.pop();
}else if(count>max){
max = count;
count = 0;
}
}
}
cout<<max<<"\n";
}
return 0;
}
最佳答案
在这段代码中:
if(!store.empty() && store.top() == '(') {
count+= 2;
store.pop();
} else if(count>max) {
max = count;
count = 0;
}
考虑最长的有效子字符串在字符串的末尾时会发生什么:您永远不会点击false分支,因此也就不会更新max
。对代码的最小更改可能是:if(!store.empty() && store.top() == '(') {
count+= 2;
store.pop();
if(count>max) {
max = count;
}
} else {
count = 0;
}
每次max
更改时,您都在哪里更新count
。可以对代码进行更多简化,例如由于
stack
仅包含相同的值,因此您可以将其替换为int
。
关于c++ - 给定仅由 '('和 ')'组成的字符串S,找出最长的有效子字符串的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63590011/