洛谷P1379题解

# 表达式括号匹配

## 题目描述

假设一个表达式有英文字母(小写)、运算符(`+`、`-`、`*`、`/`)和左右小(圆)括号构成,以 `@` 作为表达式的结束符。请编写一个程序检查表达式中的左右圆括号是否匹配,若匹配,则输出 `YES`;否则输出 `NO`。表达式长度小于 $255$,左圆括号少于 $20$ 个。

## 输入格式

一行:表达式。

## 输出格式

一行:`YES` 或 `NO`。

## 样例 #1

### 样例输入 #1

```
2*(x+y)/(1-x)@
```

### 样例输出 #1

```
YES
```

## 样例 #2

### 样例输入 #2

```
(25+x)*(a*(a+b+b)@
```

### 样例输出 #2

```
NO
```

## 提示

表达式长度小于 $255$,左圆括号少于 $20$ 个。

解法一:

#include <stdio.h>
#include <malloc.h>
#include <string.h>
//思路:栈 
struct Cell{
	char data;
	struct Cell* next;
};
struct Cell* top;//top在链头!!!!!!!!!!!!!!!!!!!! 
//Cell* Create();
void push(char k);
int pop();
int main(){
	char str[300];
	scanf("%s",str);
	int length=strlen(str);
	for(int i=0;i<length;i++){
		if(str[i]=='('){
			push(str[i]);
		}
		if(str[i]==')'){//考虑直接pop的情况 
			int tmp=pop();
			if(tmp==-1){
				printf("NO");
				return 0;
			}
		}
	}
	if(top==NULL){
		printf("YES");
	}
	else{
		printf("NO");
	}
	return 0;
}
void push(char k){
	Cell* tmp;
	tmp=(Cell*)malloc(sizeof(struct Cell));
	tmp->data=k;
	if(top==NULL){
		top=tmp;
		tmp->next=NULL;
	}
	else{
		tmp->next=top;
		top=tmp;
	}
}
int pop(){
	if(top==NULL){
		return -1;
	}
	Cell* tmp;
	tmp=top;
	top=top->next;
	free(tmp);
	return 1;
}

解法二: 

#include <stdio.h>
#include <malloc.h>
#include <string.h>
//思路:(进来,num加一,)进来,num减一,num<0,匹配失败 
int main(){
	char str[300];
	scanf("%s",str);
	int length=strlen(str);
	int num=0;
	for(int i=0;str[i]!='@';i++){
		if(str[i]=='('){
			num++;
		}
		if(str[i]==')'){
			num--;
		}
		if(num<0){
			printf("NO");
			return 0;
		}
	}
	if(num==0)
	{
		printf("YES");
		return 0;
	}
	else{
		printf("NO");
		return 0; 
	}
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值