-
Notifications
You must be signed in to change notification settings - Fork 3
/
14、括号匹配算法.cpp
64 lines (56 loc) · 1.39 KB
/
14、括号匹配算法.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include<iostream>
#include<stack>
using namespace std;
typedef unsigned char boolean;
#define TRUE 1
#define FALSE 0
boolean backetMatch(char *str);
boolean backetMatch(char *str){
stack<int> s;
int i = 0;
while(str[i]){
if(s.empty()){
s.push(str[i]);
}else{
if(s.top() == ')' || s.top() == ']' || s.top() == '}'){
return FALSE; //首先出现右括号的,肯定是不匹配的;
}
if(s.top() == '('){ //为'('的情况
if(str[i] == ')'){
s.pop();
}else{
s.push(str[i]);
}
}else if(s.top() == '['){ //为'['的情况
if(str[i] == ']'){
s.pop();
}else{
s.push(str[i]);
}
}else if(s.top() == '{'){ //为'{'的情况
if(str[i] == '}'){
s.pop();
}else{
s.push(str[i]);
}
}
}
i++;
}
if(s.empty()){
return TRUE;
}else{
return FALSE;
}
}
int main(void){
char *str = "({[])}";
boolean flag;
flag = backetMatch(str);
if(flag){
printf("括号匹配\n");
}else{
printf("括号不匹配\n");
}
return 0;
}