【问题描述】
假设一个输入字符串中包含圆括号、方括号和花括号三种类型的括号,以及其它一些任意字符.编写程序,判别串中的括号是否正确匹配,即:
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;
}