括号匹配问题
将左括号的下标压入栈,最后根据栈是否为空判断是否有左括号未匹配成功,以及未匹配成功左括号下标的位置;如果当前字符为右括号,判断栈是否为空,不为空则匹配成功,执行出栈,否则匹配失败。
参考代码:
#include<cstdio>
#include<stack>
#include<string>
#include<iostream>
using namespace std;
int main()
{
stack<int> s;
string str;
cin>>str;
int l=str.size();
string answer(l,' ');
for(int i=0;i<l;i++)
{
if(str[i]=='(')
s.push(i);
if(str[i]==')')
{
if(!s.empty())
s.pop();
else
answer[i]='?';
}
}
while(!s.empty())
{
answer[s.top()]='$';
s.pop();
}
cout<<str<<endl;
cout<<answer<<endl;
return 0;
}