码迷,mamicode.com
首页 > 其他好文 > 详细

表达式括号匹配配对判断问题

时间:2016-10-05 17:20:48      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

 1 #include <iostream>
 2 #include <string>
 3 #include <cstdio>
 4 #include <stack>
 5 using namespace std;
 6 
 7 int main()
 8 {
 9     int n;
10     string ch;
11     cout << "输入表达式数目: ";
12     cin >> n;
13     while (n--) {
14         stack<char> check;
15         int flag = 0;
16         cout << "输入表达式: ";
17         cin >> ch;
18         int len = ch.size();
19         int i = 0;
20         for (i = 0; i < len; i++) {
21             //"("、")"、"["、"]"、"{"、"}"、"<"、">"
22             if (ch[i] == ( || ch[i] == [ || ch[i] == { || ch[i] == <) {
23                 check.push(ch[i]); flag = 0; //左括号直接进栈
24             }
25             else if (ch[i] == ) || ch[i] == ] || ch[i] == } || ch[i] == >) {
26                 if (check.empty()) {          //遇到右括号时,栈顶为空则为不匹配
27                     flag = 1; break;
28                 }
29                 else {
30                     if ((check.top() == ( && ch[i] == )) || (check.top() == [ && ch[i] == ]) ||
31                         (check.top() == { && ch[i] == }) || (check.top() == < && ch[i] == >)) {
32                         flag = 0; check.pop();     //出栈左括号,继续判断
33                     }
34                     else {                         //如果左右不匹配,则退出判断
35                         flag = 1; break;           
36                     }
37                 }
38             }
39         }
40         if (check.empty() && !flag) { //如果栈为空,且没有右括号出现--匹配
41             printf("匹配\n");
42         }
43         else if (!check.empty() && !flag){
44             cout << "不匹配: 多左括号" << check.top() << endl;
45         }
46         else if (flag && check.empty()) {
47             cout << "不匹配: 多右括号" << ch[i] << endl;
48         }
49         else if (flag && !check.empty()) {
50             switch(ch[i]) {
51                 case ) : cout << "不匹配: " << check.top() 
52                                 << "" << ch[i] << "匹配错\n"; break;
53                 case ] : cout << "不匹配: " << check.top() 
54                                 << "" << ch[i] << "匹配错\n"; break;
55                 case } : cout << "不匹配: " << check.top() 
56                                 << "" << ch[i] << "匹配错\n"; break;
57                 case > : cout << "不匹配: " << check.top() 
58                                 << "" << ch[i] << "匹配错\n"; break;
59                 default : cout << "不匹配\n"; break;
60             }
61         } 
62         cout << endl; 
63     }
64     return 0;
65 }

 

表达式括号匹配配对判断问题

标签:

原文地址:http://www.cnblogs.com/douzujun/p/5932257.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!