8-2 括号匹配

【问题描述】
假设一个输入字符串中包含圆括号、方括号和花括号三种类型的括号,以及其它一些任意字符.编写程序,判别串中的括号是否正确匹配,即:
1.各种左、右括号的个数要一致;
2.不能先出现右括号;
【输入形式】
从当前目录下correct.in文件中读入一行字符串.字符串最大长度80,不含空格.
【输出形式】
输出到当前目录下correct.out文件中.输出只有一个单词,如果括号匹配则输出“True”到文件中,否则输出“False”.在输出末尾要有一个回车符.
【输入样例】
设输入文件内容如下:
rhe+[35(fjej)w-wr3f[efe{feofds}]
【输出样例】
输出文件内容为:
False

#include<stdio.h>
#include<string.h>
#include<stack>
using namespace std;


int main()
{
	stack<char> s;
	char str[100];
	FILE *in,*out;
	char c;
	int len = 0;
	int i,j;
	char top;

	in = fopen("correct.in","r");
	out = fopen("correct.out","w");

	fscanf(in,"%s",str);
	len = strlen(str);
	printf("%s\n%d\n",str,len);


	i = 0;
	while(i<len)
	{
		c = str[i];
		if(c == '[' || c == '(' || c == '{')
			s.push(c);
		if(c == ']' || c==')' || c== '}')
		{
			if(!s.empty())
				break;
			top = s.top();
			if(c == ']' && top == '[') s.pop();
			if(c == ')' && top == '(') s.pop();
			if(c == '}' && top == '{') s.pop();

		}
		i++;
	}
	if(i == len && s.empty())
	{
		fprintf(out,"%s","True");
	}
	else
		fprintf(out,"%s","False");

	fclose(in);
	fclose(out);
	return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值