1. 程式人生 > >括號配對(用棧實現)

括號配對(用棧實現)

#include<iostream>
#include<cstdio>
#include<stack>
using namespace std;
int main()
{
	char ch;
	stack<char>mystack;
	bool isMatching = true;
	while ((ch=getchar())!='\n')
	{
		switch (ch)
		{
			case '(':
			case '[':
				mystack.push(ch);
				break;
			case ']':
			{
				if (mystack.empty()||mystack.top() != '[')//先判空 再檢查
					isMatching = false;
				else
					mystack.pop();
				break;
			}
			case ')':
			{
				if (mystack.empty()||mystack.top() !=  '(')
					isMatching = false;
				else
					mystack.pop();
				break;

			}

		}
		if (!isMatching)
			break;
	}
	if(!mystack.empty())
        isMatching=false;
	if (isMatching)
		cout << "OK" << endl;
	else
		cout << "不OK" << endl;
	return 0;
}