使用栈检查表达式的括号匹配
给定一个表达式字符串exp,编写一个程序来检查对和“{”,“}”,“(”,“)”,“[”,“]”的顺序是否在exp中是正确的。 例如,程序应该为exp =“[()] {} {[()()]()}”打印为true,对于exp =“[(])”则为false。
算法步骤
其实这种字符串有一个特点,就是如果当前字符串是“右边”的括号类型,那么它的前一个必定是与之匹配的括号。
- 声明一个字符串栈
- 遍历表达式字符串exp
- 如果当前字符是起始括号“(”,"{","["则将其入栈。
- 如果当前字符是起始括号“)”,"}","]",将栈顶弹出,如果匹配右边的括号则继续重复3和4步骤,否则表达式判断不符合要求。
- 完成遍历后,堆栈必须为空才证明字符串表达式符合要求
stack<string> stk;
//做映射的map
unordered_map<string, string> theMap =
{
{ "{", "}" },
{ "(", ")" },
{ "[", "]" }
};
//是否是左边的括号
bool isLeft(string sub)
{
return theMap.find(sub) != theMap.end();
}
//是否是右边的括号
bool isRight(string sub)
{
return std::find_if(theMap.begin(), theMap.end(), [sub](std::pair<string, string> pair)
{
return pair.second == sub;
}) != theMap.end();
}
//左边的能否和右边匹配
bool isMatch(string left, string right)
{
auto iter = theMap.find(left);
if (iter == theMap.end()) //错误的输入
{
return false;
}
return iter->second == right;
}
void clearStack()
{
while (!stk.empty())
{
stk.pop();
}
}
bool checkStringIsBalanced(string exp)
{
for (int i = 0; i < exp.size(); ++i)
{
//挨个取出字符
string sub = exp.substr(i, 1);
if (isLeft(sub))
{
stk.push(sub);
continue;
}
//队列空了但是 sub不是右边符号说明结束了
if (stk.empty())
{
return false;
}
//匹配上了说明配对成功
//Tips:也可以使用switch来匹配,不过代码可扩展性较差
if (isMatch(stk.top(), sub))
{
stk.pop();
}
else
{
return false;
}
}
return stk.empty();
}
void testMy()
{
clearStack();
string exp1("{[()]}");
cout << checkStringIsBalanced(exp1) << endl;
clearStack();
string exp2("{[()]");
cout << checkStringIsBalanced(exp2) << endl;
clearStack();
string exp3("{[)]}");
cout << checkStringIsBalanced(exp3) << endl;
clearStack();
string exp4("{[()]}[]");
cout << checkStringIsBalanced(exp4) << endl;
}
结果显示第一个和第四个可以正常匹配。