一、整体思路
使用栈这种数据结构。
遍历字符串,遇到左括号则入栈,遇到右括号则判断此时的栈顶的括号是否和右括号对应,如果是则 pop 栈顶;如果不是则直接可以判定该字符串中括号不匹配。
二、栗子
#include <stack>
#include <string>
#include <iostream>
char leftOf(char c);
bool isValid(std::string str)
{
std::stack<char> left;
for (char c : str)
{
if (c == '(' || c == '{' || c == '[')
left.push(c);
else // 字符 c 是右括号
if (!left.empty() && leftOf(c) == left.top())
left.pop();
else
// 和最近的左括号不匹配
return false;
}
// 是否所有的左括号都被匹配了
return left.empty();
}
char leftOf(char c)
{
if (c == '}')
return '{';
if (c == ')')
return '(';
return '[';
}
void show(const std::string &str)
{
if (isValid(str))
std::cout << "合法" << std::endl;
else
std::cout << "不合法" << std::endl;
return;
}
int main()
{
show("{()}");
show("{()[]])");
return 0;
}
合法
不合法
(SAW:Game Over!)