一道关于栈的问题:
题目链接如下:http://vjudge.net/problem/UVA-673;
根据模型很容易想到用栈实现,下面贴出代码:
1 #include<cstdio> 2 #include<iostream> 3 #include<algorithm> 4 #include<cmath> 5 #include<cstring> 6 #include<stack> 7 #include<string> 8 using namespace std; 9 10 //判断括号是否匹配 11 int judge(char a, char b){ 12 int key = 0; 13 if (a == '('&&b == ')') key = 1; 14 else if (a == '['&&b == ']') key = 1; 15 return key; 16 } 17 18 int main() 19 { 20 string str; 21 int n; 22 cin>>n; 23 getchar(); 24 while(n--){ 25 stack<char> s; 26 int flag = 1; 27 getline(cin, str); 28 if (str.size()%2 == 0){ 29 for (int i = 0; i < str.size(); i++){ 30 //输入左括号压栈 31 if (str[i] == '('||str[i] == '['){ 32 s.push(str[i]); 33 } 34 //输入右括号时将栈顶元素进行匹配 35 else if (!s.empty()&&judge(s.top(), str[i])){ 36 s.pop();//匹配成功则弹出栈顶元素 37 } 38 else { 39 flag = 0; 40 break; 41 } 42 } 43 } 44 else flag = 0;//数目为奇数必然不符题意 45 if (flag&&s.empty()) cout<<"Yes"<<endl; 46 else cout<<"No"<<endl; 47 } 48 49 return 0; 50 }