今天尝试着写了括号匹配的问题,只是最简单的匹配( ) [ ] 这4个符号,问题来源是ACM,目前能实现匹配,但是还达不到通过ACM的水平,仅供参考吧!!!
#include <stack>
#include <string>
#include <iostream>
using namespace std;
bool is_pair(string str)
{
cout<<"当前字符串为"<<str<<endl;
stack<char> s;
string s1=str;
char now_char; //当前读取字符
char stack_top_char; //栈顶元素
for(string::size_type i=0;i<s1.size();i++)
{
cout<<"当前i="<<i<<endl;
//当前读取的字符
now_char=s1[i];
cout<<"当前读取的字符为"<<now_char<<endl;
//栈顶元素
if(s.empty())
{
stack_top_char=now_char;
}
else
{
stack_top_char=s.top();
}
cout<<"当前栈顶元素为:"<<stack_top_char<<endl;
//匹配成功则弹出栈顶元素
if( (now_char==']' &&stack_top_char=='[') || (now_char==')' &&stack_top_char=='(') )
{
cout<<"配对成功!"<<endl;
s.pop();
}
//匹配失败则把当前元素入栈
else
{
cout<<"配对失败"<<endl;
s.push(now_char);
}
}
if(s.empty())
{
return true;
}
else
{
return false;
}
}
int main()
{
string sz_tmp;
bool b_sucess;
int nCount;
cin>>nCount;
for(int i=0;i<nCount;i++)
{
cin>>sz_tmp;
b_sucess=is_pair(sz_tmp);
if(b_sucess)
cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
}