问题:
输入一个带有 '(' 、')'的字符串,编写程序判断左右括号个数是否匹配。
输入:(4+3)*5/((34+2)-64)
思路:
| 若有左括号压入栈中
输入字符串--->遍历各字符---> | --->判断栈是否为空--->空--->匹配
| 若有右括号进入判断--->栈为空--->括号不匹配 --->不空--->不匹配
--->栈不空--->将栈顶弹出
c++代码:
#include<stack>
#include<string>
#include<iostream>
using namespace std;
bool matchParenthesis(const string& s)
{
stack<char> let;
string::size_type len = s.length();
for(string::size_type i=0;i<len;i++)
{
char a = s.at(i);
if(a=='(')
let.push(a);
else if(a==')')
{
if(let.empty())
{
cout<<"false"<<endl;
return false;
}
let.pop();
}
}
if(let.empty())
{
cout<<"true"<<endl;
return true;
}
else
{
cout<<"false"<<endl;
return false;
}
}
int main(void)
{
string s;
cout<<"please input string:";
cin>>s;
matchParenthesis(s);
}