括号检查器代码的测试用例不正确.对于'(()'输出应该是'不平衡'但我得到'平衡' [英] test case incorrect for paranthesis checker code. For '(()' output sould be 'not balanced' but i'm getting 'balanced'

查看:31
本文介绍了括号检查器代码的测试用例不正确.对于'(()'输出应该是'不平衡'但我得到'平衡'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个表达式字符串 exp.检查 {,"}","(,")","[,"]" 在 exp 中的对和顺序是否正确.例如,程序应该为 exp = [()]{}{[()()]()}"' 打印 'balanced'不平衡' for exp = [(])"

Given an expression string exp. Examine whether the pairs and the orders of "{","}","(",")","[","]" are correct in exp. For example, the program should print 'balanced' for exp = "[()]{}{[()()]()}" and 'not balanced' for exp = "[(])"

输入

输入的第一行包含一个整数 T,表示测试用例的数量.每个测试用例都由一个表达式字符串组成,单独一行.

The first line of input contains an integer T denoting the number of test cases. Each test case consists of a string of expression, in a separate line.

输出

如果括号是平衡的,则打印 'balanced' 不带引号,否则在单独的行中打印 'notbalanced'.

Print 'balanced' without quotes if the pair of parenthesis is balanced else print 'not balanced' in a separate line.

约束

1 ≤ T ≤ 100
1 ≤ |s| ≤ 105

例子

输入:

3
{([])}
()
([]

输出

balanced
balanced
not balanced

#include <iostream>
#include <cstring>
#include <stack>
using namespace std;

int main() {
    //code
    int t;cin>>t;
    while(t--) {
        string s;
        stack<char> st;
        int i=0,flag =1;
        getline(cin,s);
        int n = s.size();
        while(s[i] != '') {
            if((s[i] == '{') || (s[i] == '[') || (s[i] == '(')) {
                st.push(s[i]);
            }
            else if(!st.empty() && ((st.top() == '{' && s[i] == '}') || 
            (st.top() == '[' && s[i] == ']') || (st.top() == '(' && s[i] == ')'))) st.pop();
            else {
                flag = 0;
                break;
            }
            i++;
        }
        (st.empty() && flag) ? cout<<"balanced
" : cout<<"not balanced
";
    }
    return 0;
}

推荐答案

用调试器单步执行你的代码,第一次循环你的字符串是空的.

Stepping through your code with a debugger, the first time through the loop your string is empty.

这是因为 cin >>t 在第一行的换行符处停止读取,第一行 getline(cin, s) 收到一个空字符串.

This is because cin >> t stops reading at the newline character of the first line, and the first getline(cin, s) line receives an empty string.

cin >> 之后直接调用 getline(cin, dummy_string)t 读取该行的其余部分,或切换循环以使用 cin >>s 代替.

这篇关于括号检查器代码的测试用例不正确.对于'(()'输出应该是'不平衡'但我得到'平衡'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆