uva673 - Parentheses Balance
来源:互联网 发布:上虞宇石网络怎么样 编辑:程序博客网 时间:2024/05/20 18:53
题意:
括号匹配, 按以下规则:
1. 若字符串为空, 则正确.
2. 若 A、B 皆正确, 则 AB 也正确.
3. 若 A 正确, 则 (A) 与 [A] 都正确.
即要求括号与中括号都要匹配.
思路:
使用栈, 如果当前字符与栈顶字符匹配(必须先进去的是左括号,外面的是右括号才算是匹配的):
1. 当前字符为 ')', 栈顶字符为 '(';
2. 当前字符为 ']', 栈顶字符为 '[';
则将栈顶字符出栈, 否则将当前字符入栈; 直至所有字符都操作完成, 若栈为空, 则整个字符串正确, 否则不正确.
要点:
当 stack 为空时, 调用 top 会返回段错误.
#include<iostream>#include<string>#include<cstdio>#include<cstring>#include<vector>#include<algorithm>#include<cctype>#include<iterator>#include<assert.h>#include<stack>using namespace std;//判断字符是否为括号的一部分()[]bool isParenthese(char c){ return (c == '(') || (c == ')') || (c == '[') || (c == ']') ;}//判断两个char是否匹配,如(),[]//必须是先进去的是左括号,外面的是右括号才算是匹配bool isMatch(char left, char right){ return (left == '(' && right == ')') || (left == '[' && right == ']');}//判断c与stk的top是否匹配bool isMatchTop(const stack<char>& stk, char c){ if(stk.empty()) return false; return isMatch(stk.top(), c);}//判断一行是否正确,类似后缀表达式运算,用一个栈来存储//当前字符与栈顶匹配时,就把栈顶出栈,否则把当前字符出栈bool isCorrect(const string& line){ stack<char> stk; for(int i = 0; i <line.size(); i++){ if(!isParenthese(line[i])) return false; if(isMatchTop(stk, line[i])){ stk.pop(); }else{ stk.push(line[i]); } } //若为空,则说明匹配 return stk.empty();}int main(){ int numCase; cin >> numCase; cin.ignore(); string line; while(numCase--) { getline(cin, line); if(isCorrect(line)){ cout << "Yes" <<endl; }else { cout << "No" <<endl; } } return 0;}
0 0
- uva673 Parentheses Balance
- UVA673 :Parentheses Balance
- UVA673- Parentheses Balance
- uva673-Parentheses Balance
- UVA673 Parentheses Balance
- uva673 - Parentheses Balance
- UVA673 - Parentheses Balance
- UVa673 Parentheses Balance
- UVA673 Parentheses Balance
- UVA673 Parentheses Balance
- uva673 Parentheses Balance
- uva673 Parentheses Balance
- uva673 - Parentheses Balance(栈)
- UVA673--Parentheses Balance
- uva673 Parentheses Balance(模拟+栈)
- Uva673——Parentheses Balance
- Uva673 Parentheses Balance(栈)
- uva673( Parentheses Balance)—线性表
- args问题
- 可阻塞的队列(十八)
- Abstract关键字
- svn常用命令汇总
- PAT A1042 Shuffing Machine
- uva673 - Parentheses Balance
- 使用httpclient实现http接口调用实例
- hBase-thrift 实践(java)
- smali 语法详解
- poj1741树分治
- Android线程池的经典使用
- lucene搜索实例解析
- HDU 4280 Island Transport(SAP)
- 如何android google map key