您的位置:首页 > 其它

UVA673--Parentheses Balance

2016-10-13 21:17 387 查看
题意:

输入一个包含()和[]的括号序列,判断是否合法:

空串合法;

如果A、B都合法,则AB合法

如果A合法,则(A)和[A]合法

思路:

借助栈,左括号入栈,右括号如果匹配,栈顶出栈,继续,否则不合法。注意输入空行也合法。

代码:

#include<iostream>
#include<string>
#include<stdio.h>
#include<stack>
using namespace std;
int main() {
int n;
cin >> n;
getchar();
while (n--) {
string str;
stack<char> st;
bool ok = true;
getline(cin, str);
if (str.empty()) {
cout << "Yes" << endl;
continue;
} else {
for (int i = 0; i < str.size(); i++) {
if (str[i] == '(' || str[i] == '[')
st.push(str[i]);
else if (str[i] == ')') {
if (st.empty())
st.push(str[i]);
if (st.top() == '(')
st.pop();
} else if (str[i] == ']') {
if (st.empty())
st.push(str[i]);
if (st.top() == '[')
st.pop();
}
}
}
cout << (st.empty() ? "Yes" : "No") << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: