括号匹配

对于给定的一组括号问题:(),{},[].

若其满足一一对于关系,如:(()[]{}),[[({})[]]],(([]{})), 等类似,则其满足括号相对应匹配,而如果是:[{}}{}],()),{){[]}},等类似就不满足括号的匹配.

那么首先我们可以先建立一个栈,若遇到 (,{,[ 则我们把它放入栈顶,若遇到 ),},] 则我们检验栈顶元素是不是于它相对应的符号,是的话我们就把栈顶的元素退栈,若不是我们则返回flase.

代码实现:

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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <stdio.h>
#include <stdlib.h>

int push (char *a,int top,char b); //进栈

int pop (char *a,int top); //出栈

int get_push(char *a,int top); // 查找栈顶的元素



int push (char *a,int top,char b){
a[++top] = b;
return top;
}

int pop (char *a,int top ){
if (top==-1){
printf("空栈");
return -1;
}
printf("出栈元素:%c\n",a[top]);
top--;
return top;
}

int get_push (char *a,int top){
printf("栈顶元素为:%c\n",a[top]);
return a[top];

}
bool is_empty (char *a){
return a[0] == 0;
}

//括号匹配问题
bool brace_match (char *a,int top){
char stack[100];
//char brace[3]={'(','[','{'};
int lena =sizeof(a)/sizeof(a[0]);
for (int i=0;i<lena;i++){
if (a[i]=='('||a[i]=='['||a[i]=='{'){
top = push(stack,top,a[i]);
continue;
}else if(is_empty(stack))//a[i]=[']','}',')'];
{
return false;
}else if(a[i]==')'&&get_push(stack,top)=='('){
top = pop(stack,top);
continue;
}else if(a[i]==']'&&get_push(stack,top)=='['){
top = pop(stack,top);
continue;

}else if(a[i]=='}'&&get_push(stack,top)=='{'){
top =pop(stack,top);
continue;
}else{
return false;
}
}
// 这时如果括号是相对匹配的,那么栈内元素应当为0;即对于的top=-1.
if (top == -1)
return true;
else
return false;
}

int main(){

// char a[100];
// int top = -1;
// top=push(a, top, 'a');
// top=push(a, top, 'b');
// top=push(a, top, 'c');
// top=push(a, top, 'd');
// top=pop(a, top);
// top=pop(a, top);
// top=pop(a, top);
// top=pop(a, top);
// top=pop(a, top);
// printf("\n%d ",is_empty(a));//0表示is_empty为false;即栈不为空;1相反

int top =-1;
char b[]={'[',']','{','}'};
printf("%d",brace_match(b,top));
system("pause");
return 0;
}

输出结果

栈顶元素为:[
出栈元素:[
栈顶元素为:{
出栈元素:{
1

和我们预期的吻合.