数据结构—括号匹配

/*
	栈的应用:括号配对
*/
#include
#include
#include
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;
}

运行结果
数据结构—括号匹配_第1张图片

你可能感兴趣的:(数据结构,数据结构,栈,stack)