题意:
输入一个括号序列,判断是否合法
要点:
栈的水题,注意空行也合法以及每次要清空栈就行了。话说自己写的就是丑,而且中间没有考虑直接失败的例子,每次都得全部读完,时间复杂度不是很好,不过AC也就行了
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<stack>
using namespace std;int main()
{int t;char ch[1000];scanf("%d", &t);getchar();stack<char> s;while (t--){while(!s.empty())//每次要清空栈s.pop();gets_s(ch);int n, i;n = strlen(ch);for (i = 0; i < n; i++){if (s.empty())s.push(ch[i]);else{if (ch[i] == '(' || ch[i] == '[')s.push(ch[i]);else{char c = s.top();if (c == '('&&ch[i] == ')')s.pop();if (c == '['&&ch[i] == ']')s.pop();if (c == '('&&ch[i] == ']')s.push(ch[i]);if (c == '['&&ch[i] == ')')s.push(ch[i]);}}}if (!s.empty())printf("No\n");elseprintf("Yes\n");}return 0;
}