【NYOJ】Nanyang Institute of Technology Question 2 Bracket Matching

Hello everyone, I'm here to write a water question again... But I still did it for a long time...

parentheses problem

Time Limit: 3000  ms | Memory Limit: 65535  KB
Difficulty: 3
describe
Now, there is a sequence of parentheses, please check whether the parentheses are matched.
enter
Enter a number N (0<N<=100) in the first line, indicating that there are N groups of test data. The following N lines input multiple sets of input data, each set of input data is a string S (the length of S is less than 10000, and S is not an empty string), and the number of test data sets is less than 5 sets. Data guarantee that S only contains four characters "[", "]", "(", ")"
output
The output of each set of input data occupies one line. If the brackets contained in the string are paired, output Yes, if not, output No.
sample input
3
[(])
(])
([[]()])
Sample output
No
No
Yes

When you look at the title, eh, you know it must be a stack, right?

main part

If it is a left parenthesis, push it to the stack

If the closing bracket can be matched, pop the stack

otherwise not match

code show as below

#include<iostream>
#include<cstring>
using namespace std;
int main(){
	int n;	
	const int MAX = 10005;
	char s[MAX];
	char p[MAX];
	cin>>n;
	for(int i=0;i<n;i++){
		memset(p,0,sizeof(p));
		bool flag= true;
		cin>>s;
		int len ​​= strlen(s);
		if(len%2){
			cout<<"No"<<endl;
			continue;
		}
		int k=0;
		for(int j=0;j<len;j++){
//			cout<<j<<"	"<<p<<endl;
			if(s[j]=='['||s[j]=='('){
				p[k++]=s[j];
			}else if((s[j]==']'&&p[k-1]=='[')||(s[j]==')'&&p[k-1]=='(')){
				k--;
			}else flag=false;
//			cout<<j<<"	"<<p<<k<<" "<<flag<<endl;
		}
		if(flag) cout<<"Yes"<<endl;
		else cout<<"No"<<endl;
	}
	return 0;
}
The middle comment is to see the middle output. The main reason is that I wrote the code wrong. At the beginning, the corner mark after p was j-1. It can be said that I didn’t think about it at all. Later, I found that I had written the right and left brackets in reverse. no wonder...

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326860819&siteId=291194637