题解
【入门】括号匹配
2 条题解
-
0
1. 解题思路
使用普通字符数组模拟栈。遇到左括号就入栈,遇到右括号必须与最近尚未匹配的左括号配对,配对后出栈。扫描中不匹配立即判为no,全部扫描完且栈为空才判为yes。
2. 坑点和注意事项
右括号出现时,先检查栈是否为空,再访问t−1位置;左括号全部压入后仍未弹出,也是不匹配。数组按输入长度申请,最后释放;不能对长度为0的string直接用下标写入。本题只含圆括号和方括号,输出yes或no。
3. 复杂度
- 时间复杂度:O(n),每个字符最多入栈、出栈各一次。
- 空间复杂度:O(n),字符数组模拟栈。
/* 思路:用普通字符数组模拟栈,左括号入栈,右括号与栈顶匹配。 关键:右括号只能匹配最近一个未配对的左括号。 坑点:先检查栈是否为空,再读取栈顶;结束时栈也必须为空。 时间复杂度:O(n)。 空间复杂度:O(n);按输入长度申请普通字符数组,不使用stack或vector。 */ #include <bits/stdc++.h> using namespace std; int main() { string s; cin >> s; char *a = new char[s.size()]; int t = 0; bool flag = true; for (int i = 0; i < (int)s.size(); i++) { if (s[i] == '(' || s[i] == '[') { a[t++] = s[i]; } else { // 栈顶下标为t-1,必须在确认t>0后才能访问。 if (t == 0 || (s[i] == ')' && a[t - 1] != '(') || (s[i] == ']' && a[t - 1] != '[')) { flag = false; break; } t--; } } delete[] a; cout << (flag && t == 0 ? "yes" : "no") << endl; return 0; } -
0
#include<bits/stdc++.h> using namespace std; string a,s; int top=0; int main() { cin>>a; for(int i=0;i<a.size();i++){ if(a[i]=='('||a[i]=='['){ s[++top]=a[i]; } else if(a[i]==')'&&s[top]=='('&&top>0){ top--; }else if(a[i]==']'&&s[top]=='['&&top>0){ top--; }else{ cout<<"no"; return 0; } } if(top==0){ cout<<"yes"; }else{ cout<<"no"; } return 0; }
- 1