用栈写一个括号匹配的小代码玩玩

#include <iostream>
#include <deque>
#include <string>
#include <vector>
#include <stack>

using namespace std;

typedef pair<char,char> match_token;
bool find_token(const vector<match_token>& vec,char ch,match_token& token);
bool reseach(string& match, vector<match_token>& vec);

void init_match_token(vector<match_token>& vec);

int main(int argc, char *argv[])
{

	string match_str("{[()]()}[}");
	//cout<<match_str.size();
	vector<match_token> token;
	init_match_token(token);
	
	bool rs = reseach(match_str,token);
	
	if(rs)
		cout<< "match!!!!!!!!!!!"<<endl;
	else
		cout<< "no match~~~~~~~~~~"<<endl;
	
}

void init_match_token(vector<match_token>& vec)
{
	vec.push_back(match_token('{','}'));
	vec.push_back(match_token('[',']'));
	vec.push_back(match_token('(',')'));	
}

bool reseach(string& match, vector<match_token>& vec)
{
	if (match.size()%2!=0)
		return false;
	stack<match_token> s;
	for(int i=0;i<match.size();i++)
	{
		char ch = match.at(i);
		match_token t;
		if (s.empty())
		{
			if(find_token(vec,ch,t))
		 		s.push(t);
 			else
 				return false;
		}
		else
		{
			if(s.top().second == ch)
			{
				s.pop();
			}
			else
			{
				if(find_token(vec,ch,t))
		 			s.push(t);
 				else
 					return false;
			}
		}
	}
	
	if(s.empty()) 
		return true;
	else 
		return false;
}

bool find_token(const vector<match_token>& vec,char ch,match_token& token)
{
	for(int i=0;i<vec.size();i++)
	{
		if(ch == vec[i].first)
		{
			token = vec.at(i);
			return true;
		}		
	}
	return false;	
}

你可能感兴趣的:(C++,栈)