test case incorrect for paranthesis checker code. For '(()' output sould be 'not balanced' but i'm getting 'balanced' [duplicate]

我的梦境 提交于 2020-07-16 09:32:05

问题


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 = “[(])”

Input

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.

Output

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

Constraints

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

Example

Input:

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

Output

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] != '\0') {
            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\n" : cout<<"not balanced\n";
    }
    return 0;
}

回答1:


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

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.

Simply call getline(cin, dummy_string) after cin >> t to read the rest of the line, or switch your loop to use cin >> s instead.



来源:https://stackoverflow.com/questions/61792911/test-case-incorrect-for-paranthesis-checker-code-for-output-sould-be-not

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!