写在前面:为了使得代码简洁使用了goto语句,后续将尝试重写以进一步简化代码,删除goto语句,并在闲时加入算法的JAVA实现。
The input string contains only 4 types of brackets, (), [], <> and {}. The goal is to determine whether each sequence of brackets is matched. If the input string has multiple levels of enclosure, the order of brackets must be <>, (), [], {} from inside to outside.
For example, if we input: [()], output should be ‘YES’, while input ([]) or [(], output should be ‘NO’.
样例输入输出
输入:
5
{}{}<><>()()[][]
{{}}{{}}<<>><<>>(())(())[[]][[]]
{{}}{{}}<<>><<>>(())(())[[]][[]]
{<>}{[]}<<<>><<>>>((<>))(())[[(<>)]][[]]
<}{{[]}<<<>><<>>>((<>))(())[[(<>)]][[]]
输出:
YES
YES
YES
YES
NO
//Brackets Matching
// 2020.3.2
// J.York
#include<iostream>
#include<string>
#include<stack>
using namespace std;
int getrank(char c) {
if (c == ‘<‘)
return 1;
if (c == ‘(‘)
return 2;
if (c == ‘[‘)
return 3;
if (c == ‘{‘)
return 4;
if (c == ‘>‘)
return -1;
if (c == ‘)‘)
return -2;
if (c == ‘]‘)
return -3;
if (c == ‘}‘)
return -4;
}
int main() {
int n;
string s;
cin >> n;
int* array1 = new int[n];
for (int i = 0; i < n; i++)
{
stack<char>charstack;
cin >> s;
if (s.length() % 2 == 1)
{
array1[i] = 0;
goto mark1;;
}
for (int k = 0; k < s.length(); k++)
{
if (charstack.empty()) {
if (getrank(s[k]) > 0)
{
charstack.push(s[k]);
}
else
{
array1[i] = 0;
goto mark1;;
}
}
else {
if (getrank(s[k]) > 0)
{
if (getrank(s[k]) <= getrank(charstack.top())) {
charstack.push(s[k]);
}
else
{
array1[i]