3、输入一串字符串,其中有普通的字符与括号组成(包括‘(’、‘)’、‘[’,']'),要求验证括号是否匹配,如果匹配则输出0、否则输出1.
Smpleinput:dfa(sdf)df[dfds(dfd)] Smple outPut:0
思路:最简单的数据结构,栈的问题,遇到左括号就入栈,遇到右括号就比较,如果匹配就继续,如果不匹配就结束,返回1.
#include<iostream>
#include<stack>
#include<string>
using namespace std;
bool pipei(const string &);//处理函数
int main()
{
string str;//用string 比char数组简单一些
cin>>str;
cout<<pipei(str);
}
bool pipei(const string & str)
{
stack<char> ss;
char c;
for(int i = 0 ;i< str.size(); i++) //具体处理的思路
{
if(str[i] == '(' ||str[i] == '[' )
ss.push(str[i]);
else if(str[i] == ']' ){
c = ss.top();
if (c != '[')
return true;
else
ss.pop();
}
else if(str[i] == ')' ){
c = ss.top();
if (c != '(')
return true;
else
ss.pop();
}
}
if (ss.empty()) //判断栈是否为空
return false;
else
return true;
}