问题描述
给定一个表达式字符串 exp.检查 {,"}","(,")","[,"]"
在 exp 中的对和顺序是否正确.例如,程序应该为 exp = [()]{}{[()()]()}"
和 ' 打印
for 'balanced'
不平衡'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)
tcin >>s
代替.
这篇关于括号检查器代码的测试用例不正确.对于'(()'输出应该是'不平衡'但我得到'平衡'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!