挺简单的问题,判断一串包含'('')''['']'括号的字符串是否匹配,在查打印匹配括号问题时查到的,堆栈好久不用了权当熟悉一下吧:
#include <iostream>
#include <string>
#include <stack>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
string pairstr;
cin>>pairstr;
stack<char> st;
bool flag = true;
for(unsigned int i=0;i<pairstr.size()&flag;i++)
{
switch(pairstr[i])
{
case '(':
case '[':
case '{':
st.push(pairstr[i]);
break;
case ')':
if(st.top()=='(')
{
st.pop();
}else
{
cout<<"Wrong Found"<<endl;
flag = false;
}
break;
case ']':
if(st.top()=='[')
{
st.pop();
}else
{
cout<<"Wrong Found"<<endl;
flag = false;
}
break;
case '}':
if(st.top()=='{')
{
st.pop();
}else
{
cout<<"Wrong Found"<<endl;
flag = false;
}
break;
default:
cout<<"Invalid input"<<endl;
flag = false;
break;
}
}
if(flag)
{
cout<<"Correct"<<endl;
}
return 0;
}