问题 A: 括弧匹配检验(check)
时间限制: 1 Sec 内存限制: 128 MB
提交: 132 解决: 30
[提交] [状态] [命题人:外部导入]
题目描述
假设表达式中允许包含两种括号:圆括号和方括号,其嵌套的顺序随意,如([ ]())或[([ ][ ])]等为正确的匹配,[( ])或([ ]( )或 ( ( ) ) )均为错误的匹配。
现在的问题是,要求检验一个给定表达式中的括弧是否正确匹配?
输入一个只包含圆括号和方括号的字符串,判断字符串中的括号是否匹配,匹配就输出 “OK” ,不匹配就输出“Wrong”。输入一个字符串:[([][])],输出:OK
输入
输入仅一行字符(字符个数小于 255)
输出
匹配就输出 “OK” ,不匹配就输出“Wrong”。
样例输入 Copy
[(])
样例输出 Copy
Wrong
这题主要是运用栈来判断括号的对应,以及对题目解读的严谨
这是我第一次打的代码,得了89
#include<bits/stdc++.h>
using namespace std;
stack<char> s;
stack<char> h;
char a[1001];
//int x[11];
int main(){
gets(a);
int len=strlen(a);
for(int i=0;i<=len;i++){
if(a[i]=='(')//分开判断(,[(其实放一起也不是不可以,只是个人
//感觉要难理解一些
s.push(1);//入栈
if(a[i]==')')
if(s.empty()){//没有所对应的的前括号
cout<<"Wrong";
return 0;
}else
s.pop();
if(a[i]=='[')//同理
h.push(1);
if(a[i]==']')
if(h.empty()){
cout<<"Wrong";
return 0;
}else
h.pop();
}
if(s.empty() && h.empty() )cout<<"OK";//判断没有多余的括号才OK
else cout<<"Wrong";
//下面是我这个sb用的暴力
// for(int i=0;i<len;i++){
// if(a[i]=='('){
// x[1]++;
// }else if(a[i]=='['){
// x[2]++;
// }else if(a[i]==')'){
// x[1]--;
// }else if(a[i]==']'){
// x[2]--;
// }
// if(a[1]==0 && a[2]==0 && a[3]==0){
// cout<<"OK";
// }else{
// cout<<"Wrong";
// return 0;
// }
// }
return 0;
}
这是正解:
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int stack[21];
char str[256];
int main(){
int i,len,top=0;
cin>>str;
len=strlen(str);
for(i=0;i<len;i++){
if(str[i]=='(')
stack[++top]=str[i];
else if(str[i]==')'){
if(top!=0&&stack[top]=='(')
top--;
else{
cout<<"Wrong";//如果top是')'或者'['或者‘]’都不可能最终匹配
return 0;
}
}
else if(str[i]=='[')
stack[++top]=str[i];
else if(str[i]==']'){
if(top!=0&&stack[top]=='[')
top--;
el