【题目描述】
字符串中只含有括号 (),[],<>,{},判断输入的字符串中括号是否匹配。如果括号有互相包含的形式,从内到外必须是<>,(),[],{},例如。输入: [()] 输出:YES,而输入([]),([)]都应该输出NO。
【输入】
第一行为一个整数n,表示以下有多少个由括好组成的字符串。接下来的n行,每行都是一个由括号组成的长度不超过255的字符串。
【输出】
在输出文件中有n行,每行都是YES或NO。
【输入样例】
5
{}{}<><>()()[][]
{{}}{{}}<<>><<>>(())(())[[]][[]]
{{}}{{}}<<>><<>>(())(())[[]][[]]
{<>}{[]}<<<>><<>>>((<>))(())[[(<>)]][[]]
<}{{[]}<<<>><<>>>((<>))(())[[(<>)]][[]]
【输出样例】
YES
YES
YES
YES
NO
1、扫描所有的括号,左括号入栈,右括号就和栈顶的括号匹配(如果栈为空或者不匹配,就输出NO)
2、这道题,括号有优先级 从里面到外面只能是{[(<>)]}, 优先级设置
priority[0 + ‘{’] = 0,
priority[0 + ‘[’] = 1,
priority[0 + ‘(’] = 2,
priority[0 + ‘<’] = 3;
某个括号要进栈,优先级 必须大于等于栈顶括号,否者输出No
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <stack>
#include <cctype>
using namespace std;
const int MaxN = 300;
char str[MaxN];
int priority[MaxN];
bool flag = true;
stack<char> s;
void handle(char ch)
{
if(s.empty())
{
flag = false;
return;
}
char tp = s.top(); s.pop();
if((tp == '(' && ch != ')') || (tp == '[' && ch != ']')
|| (tp == '<' && ch != '>') || (tp == '{' && ch != '}'))
flag = false;
}
int main()
{
int t;
priority[0 + '{'] = 0, priority[0 + '['] = 1, priority[0 + '('] = 2, priority[0 + '<'] = 3;
scanf("%d", &t);
while(t--)
{
flag = true;
while(!s.empty()) s.pop();
scanf("%s", str);
int n = strlen(str);
for(int i = 0; i < n; ++i)
{
if(str[i] == '(' || str[i] == '<' || str[i] == '[' || str[i] == '{')
{
if(!s.empty() && priority[0 + str[i]] < priority[0 + s.top()])
{
flag = false;
break;
}
s.push(str[i]);
}
else
handle(str[i]);
if(flag == false)
break;
}
if(flag == false || !s.empty())
{
printf("NO\n");
}else
printf("YES\n");
}
return 0;
}
/*
5
{}{}<><>()()[][]
{{}}{{}}<<>><<>>(())(())[[]][[]]
{{}}{{}}<<>><<>>(())(())[[]][[]]
{<>}{[]}<<<>><<>>>((<>))(())[[(<>)]][[]]
><}{{[]}<<<>><<>>>((<>))(())[[(<>)]][[]]
*/
/*
YES
YES
YES
YES
NO
*/
该博客讨论了如何判断字符串中的括号是否匹配,重点在于处理括号的优先级。通过扫描字符串,将左括号入栈,然后检查右括号是否与栈顶的左括号匹配。括号的优先级设定为:{<[(],并要求右括号的优先级不能低于栈顶括号。对于给定的输入样例,算法能够正确地判断YES或NO。

1372

被折叠的 条评论
为什么被折叠?



