【刷题】字符串匹配问题(strs)

字符串匹配问题(strs)
【题目描述】

字符串中只含有括号 (),[],<>,{},判断输入的字符串中括号是否匹配。如果括号有互相包含的形式,从内到外必须是<>,(),[],{},例如。输入: [()] 输出:YES,而输入([]),([)]都应该输出NO。

【输入】

第一行为一个整数n,表示以下有多少个由括号组成的字符串。接下来的n行,每行都是一个由括号组成的长度不超过255的字符串。

【输出】

在输出文件中有n行,每行都是YES或NO。

【输入样例】

5
{}{}<><>()()[][]
{{}}{{}}<<>><<>>(())(())[[]][[]]
{{}}{{}}<<>><<>>(())(())[[]][[]]
{<>}{[]}<<<>><<>>>((<>))(())[[(<>)]][[]]
><}{{[]}<<<>><<>>>((<>))(())[[(<>)]][[]]

【输出样例】

YES
YES
YES
YES
NO

此题为【STL】栈(stack)中例题的plus版
四种括弧并有优先级
笔者的解法:

#include<bits/stdc++.h>
using namespace std;
bool isMatch(char ch[]){
	stack<int> sta;
	for(int i=0;i<strlen(ch);i++){
		if(ch[i]=='<'){
			if(sta.empty()||1<=sta.top()) sta.push(1);
			else return 0;
		}
		else if(ch[i]=='('){
			if(sta.empty()||2<=sta.top()) sta.push(2);
			else return 0;
		}
		else if(ch[i]=='['){
			if(sta.empty()||3<=sta.top()) sta.push(3);
			else return 0;
		}
		else if(ch[i]=='{'){
			if(sta.empty()||4<=sta.top()) sta.push(4);
			else return 0;
		}
		else if(ch[i]=='>'){
			if((!sta.empty())&&sta.top()==1) sta.pop();
			else return 0;
		}
		else if(ch[i]==')'){
			if((!sta.empty())&&sta.top()==2) sta.pop();
			else return 0;
		}
		else if(ch[i]==']'){
			if((!sta.empty())&&sta.top()==3) sta.pop();
			else return 0;
		}
		else if(ch[i]=='}'){
			if((!sta.empty())&&sta.top()==4) sta.pop();
			else return 0;
		}
	}
	if(!sta.empty()) return 0;
	return 1;
} 

int main(){
	int n;
	char ch[100][255];
	cin>>n;
	for(int i=0;i<n;i++){
		cin>>ch[i];
	}
	for(int j=0;j<n;j++){
		if(isMatch(ch[j])) cout<<"YES"<<endl;
		else cout<<"NO"<<endl;
	}
	return 0;
}

参考答案解法:

#include<bits/stdc++.h>
using namespace std;
int a[10001]={0},b[10001]={0};
char s[10001];
void gsy(int a[]){
	int i;
	for(i=0;i<strlen(s);i++){
		//将括号转换成数字,以比较括号级别
		if(s[i]=='{') a[i+1]=1; 
		if(s[i]=='[') a[i+1]=2;
		if(s[i]=='(') a[i+1]=3;
		if(s[i]=='<') a[i+1]=4; 
		if(s[i]=='>') a[i+1]=5; 
		if(s[i]==')') a[i+1]=6; 
		if(s[i]==']') a[i+1]=7; 
		if(s[i]=='}') a[i+1]=8; 
	}
}
int main(){
	int i,n,t=0,m,j,k;
	cin>>n;
	for(i=1;i<=n;i++){
		cin>>s;t=0;
		gsy(a);
		for(j=1;j<=strlen(s);j++){
			if(a[j]<=4)//如果是左括号
			if(a[j]>=b[t]) b[++t]=a[j];//如果括号级别顺序符合,左括号进栈
			else break;
			if(a[j]>=5)//右括号进栈
			if(a[j]+b[t]==9) t--;//匹配成功,出栈
			else t++; 
		}
		if(t==0) cout<<"YES"<<endl;
		else cout<<"NO"<<endl;
	}
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值