当前位置:网站首页>Bracket matching problem (STL)

Bracket matching problem (STL)

2022-07-05 10:52:00 Yun Qian

Bracket matching problem (STL)

The implementation of a handwriting stack has been written above , The principle is the same , Now send a use STL A concise way of writing

#include <cstring>
#include <iostream>
#include <stack>
using namespace std;
bool pp(string str,int length){
	stack<char> s;
	for(int i = 0; i < length; i++){
		if(str[i] == '(' || str[i] == '[' || str[i] == '{'){
			s.push(str[i]); // If it's left parenthesis   Into the stack 
		}
		else{
			if(s.empty())
				return false;
			char topElem;
			topElem = s.top(); 
			s.pop(); 
			if(str[i] == ')' && topElem != '(')
				return false;
			if(str[i] == ']' && topElem != '[')
				return false;
			if(str[i] == '}' && topElem != '{')
				return false;
		}
	}
	return s.empty();// Judge whether it is an empty stack 
}
int main(){
	string str;
	cin >> str;
	if(pp(str,str.size()))
		cout << " The match is successful " << endl;
	else
		cout << " Matching failure " << endl;
	return 0;
}
原网站

版权声明
本文为[Yun Qian]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207051019035413.html