Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/tfs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;答错_C++_Stack - Fatal编程技术网

C++ C++;答错

C++ C++;答错,c++,stack,C++,Stack,GFG括号检查器在测试用例“[]”中显示错误答案,但当我使用自定义测试用例时,它会显示正确答案。我没有发现我的代码中有什么错误。 这是我的C++代码。 #include <bits/stdc++.h> using namespace std; int main(){ int t; cin >> t; while(t--){ string s; cin >> s; int l = s.l

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;
}
#包括
使用名称空间std;
int main(){
int t;
cin>>t;
而(t--){
字符串s;
cin>>s;
int l=s.长度();
堆栈stq;
int标志=0;
对于(int i=0;i
Input
2
[][{]
}{

为什么不编写一个函数来检查有效的偏执,并返回true或false?这样做既简洁又简单。

谢谢,我解决了这个问题。我只是在更改flag的clvalue之前使用了break语句。
Output
not balanced
not balanced
not balanced
balanced