【问题标题】:Given a string S consisting only of '(' and ')', find out the length of the longest valid substring给定一个仅由 '(' 和 ')' 组成的字符串 S,找出最长有效子字符串的长度
【发布时间】:2020-12-14 19:17:44
【问题描述】:

我知道在 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;
}

【问题讨论】:

  • 确实是调试器存在的原因。使用给定的输入数据单步执行此代码,检查变量值并根据您的期望对它们进行权衡可能会非常有启发性。无论如何,我也认为不需要堆栈。它所拥有的只是'(' 个字符,您可以使用一个简单的计数器轻松地做到这一点。

标签: c++ string data-structures stack queue


【解决方案1】:

在这段代码中:

if(!store.empty() && store.top() == '(') {
     count+= 2;
     store.pop();
} else if(count>max) {
     max = count;
     count = 0;
}

考虑当最长有效子字符串位于字符串末尾时会发生什么:您永远不会遇到错误分支,因此您永远不会更新max。对代码的最小更改可能是:

if(!store.empty() && store.top() == '(') {
     count+= 2;
     store.pop();
     if(count>max) {
         max = count;
     }
} else {
     count = 0;
}

每次count 更改时,您都在哪里更新max

可以对代码进行更多简化,例如由于stack 只包含相同的值,您可以将其替换为int

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-28
    • 1970-01-01
    • 2019-05-03
    • 1970-01-01
    • 2013-02-21
    • 1970-01-01
    • 2012-05-28
    • 2021-12-28
    相关资源
    最近更新 更多