题目链接<http://acm.zjnu.edu.cn/DataStruct/showproblem?problem_id=1002>
实验二 括号匹配判断算法
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 2202 | Accepted: 924 |
Description
假设在表达式中([]())或[([ ][ ])]等为正确的格式,[( ])或([( ))或 (( )])均为不正确的格式。基于栈设计一个判断括号是否正确匹配的算法。
Input
输入数据有多组,每组测试数据一行,一个字符串,只包含 ‘[‘ ,’]’ ,’(‘ ,‘)’ 。
Output
对于每组测试数据,若括号匹配输出yes,否则输出 no。
Sample Input
[]()[]
([[]])[)
Sample Output
yes
no
题解:
利用stack判断存储。从头到尾扫描一遍字符串,如果是左括号(无论是小的还是中的)都入栈。如果是右括号,就把当前的字符与栈的头元素比对,如果配对就栈跳出头元素,如果不配对,那么就可以把标记的flag设为0。如果是右括号,且栈内没有元素,则flag也可为0。如果扫描已经完毕,栈内仍然存在元素,那么flag也是0。
oj的原因多组输入不能用~scanf("")
#include <iostream>
#include <stdio.h>
#include <map>
#include <queue>
#include <string.h>
#include <string>
#include <stack>
using namespace std;
typedef long long LL;
int main(){
char s[10005];
stack<char>st;
while(scanf("%s",s)!=EOF){
while(!st.empty()) st.pop();
int len=strlen(s),flag=1;
for(int i=0;i<len;i++){
if(s[i]=='('||s[i]=='[')
st.push(s[i]);
else{
if(st.empty()){
flag=0;break;
}
char tmp=st.top();
st.pop();
if(s[i]==')'&&tmp=='['){
flag=0;
break;
}
else if(s[i]==']'&&tmp=='('){
flag=0;
break;
}
}
}
if(!st.empty()) flag=0;
if(flag) printf("yes\n");
else printf("no\n");
}
return 0;
}