嚴蔚敏3.18

//判斷表達式中的開、閉括號是否配對
#include <iostream>
#include <string>
using namespace std;

class MyStack
{
private:
	char Big[100];
	char Small[100];
	
public:
	int BigTop;
	int SmallTop;
	void InitStack();

	int IsBigEmpty();
	void PushBig(char c);
	void PopBig();

	int IsSmallEmpty();
	void PushSmall(char c);
	void PopSmall();
};
void MyStack::InitStack()
{
	BigTop=0;
	SmallTop=0;
}
int MyStack::IsBigEmpty()
{
	return(BigTop==0);
}
void MyStack::PushBig(char c)
{
	BigTop+=1;
	Big[BigTop]=c;
}
void MyStack::PopBig()
{
	BigTop-=1;
}

int MyStack::IsSmallEmpty()
{
	return(SmallTop==0);
}
void MyStack::PushSmall(char c)
{
	SmallTop+=1;
	Small[SmallTop]=c;
}
void MyStack::PopSmall()
{
	SmallTop-=1;
}

int main()
{
	MyStack by;
	string str;
	cout<<"請輸入一串字符串:";
	cin>>str;
	int i,j;
	by.InitStack();
	for (i=0;i<str.length();i++)
	{
		if (str.at(i)=='(')
			by.PushSmall(str.at(i));
		if (str.at(i)=='[')
			by.PushBig(str.at(i));
		if (str.at(i)==')')
		{
			if (by.IsSmallEmpty())
			{
				cout<<"小括號沒有正確配對!"<<endl;
				cout<<"無法正確配對!"<<endl;
				return 0;
			}
			else
			{
				by.PopSmall();
			}
		}
		if (str.at(i)==']')
		{
			if (by.IsBigEmpty())
			{
				cout<<"大括號沒有正確配對!"<<endl;
				cout<<"無法正確配對!"<<endl;
				return 0;
			}
			else
			{
				by.PopBig();
			}
		}
	}
	if (by.IsBigEmpty()&&by.IsSmallEmpty())
	{
		cout<<"正確配對!"<<endl;
		return 1;
	}
	else
	{
		cout<<"沒有正確配對!"<<endl;
		return 0;
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章