数据结构里面,括号的配对问题是比较经典的。在这里,我们给出STL中堆栈解决括号配对问题:
#include "vector"
#include "stack"
#include "iostream"
#include "string"
#include "windows.h"
using namespace std;
int main()
{
char left='(';
char right=')';
stack<char,vector<char>>parentStack;
string parents;
bool matching=true;
cin>>parents;
for(int i=0; i<parents.length()&&matching; i++)
{
if(parents[i]==left)
{
parentStack.push(left);
}
else if(parents[i]==right)
{
if(parentStack.empty())
{
matching=false;
}
else
{
parentStack.pop();
}
}
}
if(matching&&parentStack.empty())
{
cout<<"配对成功!"<<endl;
}
else
{
cout<<"配对失败!"<<endl;
}
Sleep(25000000);
return 0;
}
实现: