Data structure-bracket matching

/*
	栈的应用:括号配对
*/
#include<iostream>
#include<stack>
#include<string.h>
using namespace std;

void MatchBracket(char* S) {
    
    
	stack<char> stack;
	int length = strlen(S);
	for (int i = 0; i < length; i++) {
    
    
		if (S[i] == '(' || S[i] == '[' || S[i] == '{') {
    
    //左括号入栈
			stack.push(S[i]);
		}
		else if (S[i] == ')' || S[i] == ']' || S[i] == '}') {
    
    //右括号出栈,进行匹配
			if (S[i]==')' && stack.top()=='('|| S[i] == ']' && stack.top() == '['|| S[i] == '}' && stack.top() == '{') {
    
    
				stack.pop();
			}
			else {
    
    
				cout << "NO" << endl;
				break;
			}
		}
	}
	if (stack.empty())
		cout << "YES" << endl;
}

int main()
{
    
    

	char s1[] = "()";
	char s2[] = "({]]]";
	MatchBracket(s1);
	MatchBracket(s2);
	return 0;
}

operation result
Insert picture description here

Guess you like

Origin blog.csdn.net/Gentle722/article/details/106276085