== 写在前面:为了使代码更简洁地使用goto语句,随后将尝试尝试以更多的简化代码,删除goto语句,并在闲时加入算法的JAVA实现。 ==
- ##译文描述
- 输入字符串仅包含4种类型的方括号(),[],<>和{}。目的是确定每个括号序列是否匹配。如果输入带有多个级别的包围,则从内部到外部,实例,如果我们输入:[[]],输出应为’YES’,而输入([[]]或[(],输出),,,括号的顺序必须为<>,(),[],{ }。应为’NO’。
- ##输入
- 输入的第一行是整数N,表示下面有多少个字符串。接下来的N行,每行是一个包含方括号且不超过255的字符串。
- ##输出
- 输出中有N行,每行是YES或NO。
样例输入输出输入:5 {} {} <> <>()()[
] [] {{}} {{}} << >> << >>(())(())[[]] [[] ] {{}} {{}} << >> <<> >(())(())[[]] [[] ] {<>} { []} <<< >> << >>>((<>))(())[[(<> )]] [[] ]
<} {{ []} <<< >> << >>>((<>))(())[[(<>)]] [[] ]输出:是是是是否
示例代码:
//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] = 0;
goto mark1;;
}
}
else
{
if (charstack.empty())
{
array1[i] = 0;
goto mark1;;
}
else
{
if (getrank(s[k]) == -getrank(charstack.top()))
{
charstack.pop();
}
else
{
array1[i] = 0;
goto mark1;;
}
}
}
}
}
if (charstack.empty())
{
array1[i] = 1;
}
else
{
array1[i] = 0;
}
mark1:;
}
for (int i = 0; i < n; i++)
{
if (array1[i] == 0) {
cout << "NO" << endl;
}
else {
cout <<“是” << endl; }}}```