算法笔记练习 题解合集
题目
题目描述
请写一个程序,判断给定表达式中的括号是否匹配,表达式中的合法括号为”(“, “)”, “[", "]“, “{“, ”}”,这三个括号可以按照任意的次序嵌套使用。
输入
有多个表达式,输入数据的第一行是表达式的数目,每个表达式占一行。
输出
对每个表达式,若其中的括号是匹配的,则输出”yes”,否则输出”no”。
样例输入
4
[(d+f)*{}]
[(2+3))
()}
[4(6]7)9
样例输出
yes
no
no
no
思路
用input
遍历每一行待检查的字符串:
- 如果
input
遇到'('
或者[
或者{
,直接将其入栈; - 如果
input
遇到')'
或者]
或者}
,首先检查栈是否为空:
a. 若栈非空,检查input
与栈顶字符是否配对,如果配对,出栈一次,继续遍历,如果不配对,则该行不符合要求;
b. 若栈空,则该行不符合要求;
代码
#include <cstdio>
#include <stack>
#include <string>
using namespace std;
const string CATCHUP = "()[]{}";
int main() {
int n;
char input;
bool flag;
while (scanf("%d", &n) != EOF) {
getchar();
while (n--) {
flag = true;
stack<char> parentheses;
while ((input = getchar()) != '\n') {
if (input == '(' || input == '[' || input == '{')
parentheses.push(input);
else if (input == ')' || input == ']' || input == '}') {
if (parentheses.empty() || CATCHUP.find(input) - CATCHUP.find(parentheses.top()) != 1)
flag = false;
else
parentheses.pop();
}
}
if (!parentheses.empty())
flag = false;
puts(flag ? "yes" : "no");
}
}
return 0;
}