栈的应用(括号匹配):
思想:用一个栈存放左括号,遇到右括号就出栈,遇到非法情况也出栈,特殊情况单个特判!
原题链接: https://www.acwing.com/problem/content/description/3696/
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 10010;
char str[N]; //heap
char stack[N];
int top = -1;
int main()
{
cin >> str;
int n = strlen(str);
bool flag = true;
for(int i = 0;i < n;i ++)
{
if(str[i] == '(' || str[i] == '[' || str[i] == '{' || str[i] == '<')
stack[++ top] = str[i];
else if(str[i] == ')' && stack[top] == '('
|| str[i] == ']' && stack[top] == '['
|| str[i] == '}' && stack[top] == '{'
|| str[i] == '>' && stack[top] == '<' )
top --;
else
{
flag = false;
top --;
}
}
if(flag&&top<0) cout << "yes";
else cout << "no";
return 0;
}