1355:字符串匹配问题(strs)
【题目描述】
字符串中只含有括号 (),[],<>,{},判断输入的字符串中括号是否匹配。如果括号有互相包含的形式,从内到外必须是<>,(),[],{},例如。输入: [()] 输出:YES,而输入([]),([)]都应该输出NO。
【输入】
第一行为一个整数n,表示以下有多少个由括好组成的字符串。接下来的n行,每行都是一个由括号组成的长度不超过255的字符串。
【输出】
在输出文件中有n行,每行都是YES或NO。
【输入样例】
5
{}{}<><>()()[][]
{{}}{{}}<<>><<>>(())(())[[]][[]]
{{}}{{}}<<>><<>>(())(())[[]][[]]
{<>}{[]}<<<>><<>>>((<>))(())[[(<>)]][[]]
<}{{[]}<<<>><<>>>((<>))(())[[(<>)]][[]]
【输出样例】
YES
YES
YES
YES
NO
代码
#include <bits/stdc++.h>
using namespace std;
char st[256],top;
bool f(string s){
top=0;//清空栈
for(int i=0;i<s.length();i++){
switch(s[i]){
case '{': if(st[top]=='[' || st[top]=='(' || st[top] =='<') return false;
case '[': if(st[top]=='(' || st[top] =='<') return false;
case '(': if(st[top] =='<') return false;
case '<': st[++top]=s[i];break;
case ')': if(st[top--]!=s[i]-1) return 0;break;
case '>':
case ']':
case '}': if(st[top--]!=s[i]-2) return 0;break;
}
}
if(top) return false; else return true;
}
int main(){
int n;
string s;
cin>>n;
for(int i=0;i<n;i++){
cin>>s;
f(s)?cout<<"YES"<<endl:cout<<"NO"<<endl;
}
return 0;
}