重启c语言— 括号匹配

7-2 括号匹配

给定一串字符,不超过100个字符,可能包括括号、数字、字母、标点符号、空格,编程检查这一串字符中的( ) ,[ ],{ }是否匹配。

输入格式:
输入在一行中给出一行字符串,不超过100个字符,可能包括括号、数字、字母、标点符号、空格。

输出格式:
如果括号配对,输出yes,否则输出no。

输入样例1:
sin(10+20)

输出样例1:
yes

输入样例2:
{[}]

输出样例2:
no

思路:将字符串读入后,遇到左括号就入栈,遇到右括号就出栈对比,若不匹配直接打印no并结束程序,若匹配则继续进行,直至字符串全部读入结束,若全部匹配,再检查栈是否为0,若为空栈,则打印yes即可,否则意味着栈内有左括号,则说明不匹配,因此打印no。代码如下所示:

#include <stdio.h>
#include<string.h>
#include<stdlib.h>
 
typedef struct stack {
	char D[105];
	int top;
}*St;
 
St Creat();
void Push(St s, char c);
char Pop(St s);
int IsEmpty(St s);
 
int main() {
	St s;
	char t[105];
	char temp;
	int i = 0;
	s = Creat();
	gets(t);
	while (t[i] != '\0') {
		if (t[i] == '{'|| t[i] == '['|| t[i] == '(') {
			Push(s, t[i]);
		}
		else if (t[i] == '}') {
			temp = Pop(s);
			if ((!IsEmpty(s)) && (temp != '{')) {
				printf("no");
				return 0;
			}
		}
		else if (t[i] == ']') {
			temp = Pop(s);
			if ((!IsEmpty(s)) && (temp != '[')) {
				printf("no");
				return 0;
			}
		}
		else if (t[i] == ')') {
			temp = Pop(s);
			if ((!IsEmpty(s)) && (temp != '(')) {
				printf("no");
				return 0;
			}
		}
		i++;
	}
	if (IsEmpty(s)) printf("yes");
	else printf("no");
	return 0;
}
St Creat() {
	St s;
	s = (St)malloc(sizeof(struct stack));
	s->top = -1;
	return s;
}
void Push(St s, char c) {
	s->D[++s->top] = c;
}
char Pop(St s) {
	char t;
	t = s->D[s->top--];
	return t;
}
int IsEmpty(St s) {
	if (s->top == -1)
		return 1;
	else return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43723423/article/details/105729259