UVA673--Parentheses Balance
2016-10-13 21:17
387 查看
题意:
输入一个包含()和[]的括号序列,判断是否合法:
空串合法;
如果A、B都合法,则AB合法
如果A合法,则(A)和[A]合法
思路:
借助栈,左括号入栈,右括号如果匹配,栈顶出栈,继续,否则不合法。注意输入空行也合法。
代码:
输入一个包含()和[]的括号序列,判断是否合法:
空串合法;
如果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; }
相关文章推荐
- UVA673:Parentheses Balance(平衡的括号)
- UVA-673 Parentheses Balance (桟)
- uva673-Parentheses Balance
- uva-673 Parentheses Balance
- UVa 673 - Parentheses Balance
- uva 673 - Parentheses Balance
- UVA - 673 Parentheses Balance
- UVa 673 Parentheses Balance【栈】
- uva 673 Parentheses Balance
- uva 673 Parentheses Balance (平衡的括号)堆栈模拟
- Uva 673 Parentheses Balance 平衡的括号
- UVA 673 - Parentheses Balance
- UVa673_ Parentheses Balance
- UVA673 Parentheses Balance
- UVa 673 - Parentheses Balance
- STL-B Parentheses Balance (UVA-673)
- UVa 673 - Parentheses Balance
- UVa-673 Parentheses Balance(栈模拟)
- UVA 673 - Parentheses Balance
- UVa 673 - Parentheses Balance(链表)