标签:
括号配对问题:http://acm.nyist.net/JudgeOnline/problem.php?pid=2
思路:利用栈先进后出的性质,左符入,右符出。
#include<iostream> #include<string> #include<stack> using namespace std; bool check(string str) { stack<char> stack; for (int i = 0; i < str.length(); ++i) { if (str[i] == ‘(‘ || str[i] == ‘[‘ || str[i] == ‘{‘) stack.push(str[i]); //左符入栈 else if (stack.empty()) //非左符同时栈内无右符,则配对失败 return false; else if (!(stack.top() == ‘(‘ && str[i] == ‘)‘ || //栈顶与当前符号不配对,则配对失败 stack.top() == ‘[‘ && str[i] == ‘]‘ || stack.top() == ‘{‘ && str[i] == ‘}‘)) return false; else stack.pop(); //出栈,配对成功 } return stack.empty(); //空栈,配对成功 } int main() { int n = 0; cin >> n; for (int i = 0; i < n; ++i) //多次测试 { string str; cin >> str; cout << (check(str)?"Yes":"No") << endl; } }
标签:
原文地址:http://www.cnblogs.com/wangzexi/p/4733231.html