首页 > 试题广场 >

括号的匹配

[编程题]括号的匹配
  • 热度指数:1680 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
\hspace{15pt}在算术表达式中,除了加、减、乘、除等运算外,往往还有括号。在本题中,我们视括号有四种:大括号 \texttt{\{...\}},中括号 \texttt{[...]},小括号 \texttt{(...)},尖括号 \texttt{<...>}
\hspace{15pt}我们定义合法的括号表达式为:
\hspace{23pt}\bullet\,对于每一对括号,必须先有左边括号,然后才有右边括号。
\hspace{23pt}\bullet\,如果有多个括号,则每种类型的左括号和右括号的个数必须相等。
\hspace{23pt}\bullet\,对于多重括号的情形,按运算规则,从外到内的括号嵌套顺序为:大括号 \rightarrow 中括号 \rightarrow 小括号 \rightarrow 尖括号。例如,\texttt{\{[(<>)]\}}\texttt{\{()\}}\texttt{\{\{\}\}} 为一个合法的表达式,而 \texttt{([\{\}])}\texttt{\{([])\}}\texttt{[\{<>\}]} 都是非法的。
\hspace{15pt}现在给定一个仅由上述四类括号组成的括号表达式,请你判断它是否为合法的括号表达式。

输入描述:
\hspace{15pt}每个测试文件均包含多组测试数据。第一行输入一个整数 T\left(1\leq T\leq 10^4\right) 代表数据组数,每组测试数据描述如下:

\hspace{15pt}在一行上输入一个长度为 {\rm length}(s),仅由上述四类括号组成的括号表达式 s \left(1\leq {\rm length}(s) \leq 2\times 10^5\right)

\hspace{15pt}除此之外,保证单个测试文件的 {\rm length}(s) 之和不超过 2\times 10^5


输出描述:
\hspace{15pt}对于每一组测试数据,新起一行。如果表达式是合法的,输出 \texttt{YES};否则输出 \texttt{NO}
示例1

输入

5
{[(<>)]}
[()]
<>()[]{}
[{}]
{()}

输出

YES
YES
YES
NO
YES

备注:
本题已于下方时间节点更新,请注意题解时效性:
1. 2025-11-13 优化题面文本与格式。原数据存在空白行,重造数据。
头像 hujiao
发表于 2025-12-26 08:59:00
真是杂鱼呢~怎么这题都不会写阿❤。作为栈专栏的最后一题只要做了前一题就知道这题怎么写吧,这题最优解应该是 栈 + 嵌套顺序校验做法上如果是左括号就压栈,如果是右括号就判断是否 栈空 和 是否对应了左括号 如果不是栈空且对应了就出栈。但是这题要求了括号大小顺序也必须遵循,而这四个括号的左括号(只压栈左 展开全文
头像 小狐今天睡大觉
发表于 2025-12-14 02:42:44
#include <iostream> #include <map> #include <stack> using namespace std; int main() { int a; cin >> a; map<cha 展开全文
头像 Pek
发表于 2026-01-25 13:02:45
不会用map建立检查顺序,就直接简单粗暴写逻辑检验 #include <bits/stdc++.h> using namespace std; #define inf 0x3f3f3f3f #define int long long /* run this program using 展开全文
头像 周康禧
发表于 2025-12-09 10:41:15
#include <bits/stdc++.h> using namespace std; using ll = long long int; using ld = long double; using PII=pair<ll,ll>; using PIII=pair< 展开全文
头像 自由的风0450
发表于 2025-11-15 21:52:35
#include <iostream> #include <string> #include <stack> using namespace std; int getPriority(char c) { switch (c) { case 展开全文
头像 Sau_Hanson
发表于 2026-02-08 13:53:53
#include <bits/stdc++.h> using namespace std; void solve() { string s; cin>>s; stack<char>t; for(int i=0;i<s.size 展开全文
头像 游云吞鲸
发表于 2026-01-20 09:34:25
#include <bits/stdc++.h> using namespace std; bool isvalid(const string & );//引用传递,无需拷贝 int main() { int T;cin>>T; while(T--& 展开全文
头像 牛客用户098471297
发表于 2025-11-28 11:40:32
#include<bits/stdc++.h> using namespace std; #define int long long #define endl '\n' #define quick ios::sync_with_stdio(false);cin.tie(0);cout.t 展开全文
头像 Drink0318
发表于 2025-12-10 10:49:37
import sys n = int(input()) data = iter(sys.stdin.read().splitlines()) dic ={"{":"}","[":"]","(":&qu 展开全文
头像 哈基图
发表于 2026-01-29 20:30:23
#include<bits/stdc++.h> #include<unordered_map> using namespace std; int main(){ int T; cin>>T; while(T--){ unor 展开全文