【问题标题】:GFG Parenthesis Checker problem in C++ giving wrong answerC ++中的GFG括号检查器问题给出错误答案
【发布时间】:2020-11-10 17:04:12
【问题描述】:

GFG 括号检查器在测试用例“[][]”中显示错误答案,但是当我使用自定义测试用例时,它显示正确答案。我的代码没有出错。 这是我的 C++ 代码。

#include <bits/stdc++.h>
using namespace std;

int main(){

    int t;
    cin >> t;
    while(t--){
        string s;
        cin >> s;
        int l = s.length();
        stack<char> stq;
        int flag = 0;
        for (int i = 0; i < l; i++){
            if (s[i] == '(' || s[i] == '{' || s[i] == '[')
                stq.push(s[i]);
            else if (!stq.empty() && s[i] == ')' && stq.top() == '(')
                stq.pop();
            else if (!stq.empty() && s[i] == ']' && stq.top() == '[')
                stq.pop();
            else if (!stq.empty() && s[i] == '}' && stq.top() == '{')
                stq.pop();
            else{
                cout << "not balanced" << endl;
                break;
                flag = 1;
            }
        }
        if (flag == 0){
            if (stq.empty())
                cout << "balanced" << endl;
            else
                cout << "not balanced" << endl;
        }
    }
    return 0;
}

问题的链接是https://practice.geeksforgeeks.org/problems/parenthesis-checker/0#

【问题讨论】:

标签: c++ stack


【解决方案1】:

您的代码多次打印“不平衡”。

Input
2
[][{]
}{
Output
not balanced
not balanced
not balanced
balanced

您为什么不编写一个函数来检查有效的括号并返回真或假?这样会很简洁。

【讨论】:

  • 谢谢你,我有这个问题。我只是在更改标志的 clvalue 之前使用了 break 语句。
猜你喜欢
  • 2014-11-19
  • 1970-01-01
  • 1970-01-01
  • 2023-01-21
  • 1970-01-01
  • 2023-02-17
  • 1970-01-01
  • 2021-09-07
  • 1970-01-01
相关资源
最近更新 更多