问题 B: Problem E
时间限制: 1 Sec 内存限制: 32 MB题目描述
请写一个程序,判断给定表达式中的括号是否匹配,表达式中的合法括号为”(“, “)”, “[", "]“, “{“, ”}”,这三个括号可以按照任意的次序嵌套使用。
输入
有多个表达式,输入数据的第一行是表达式的数目,每个表达式占一行。
输出
对每个表达式,若其中的括号是匹配的,则输出”yes”,否则输出”no”。
样例输入
4
[(d+f)*{}]
[(2+3))
()}
[4(6]7)9
样例输出
yes
no
no
no
User: 吴锦诚 Date: 2018/7/10
#include <iostream>
#include <string>
#include <stack>
#include <map>
#include <math.h>
using
namespace
std;
#define MIN_VALUE 1e-8
string str;
stack<
char
> sta;
map<
char
,
double
> maps;
void
setMaps()
{
maps[
'('
] = 0.1;
maps[
'['
] = 0.2;
maps[
'{'
] = 0.3;
maps[
')'
] = 1.1;
maps[
']'
] = 1.2;
maps[
'}'
] = 1.3;
}
bool
equ(
double
a,
double
b)
{
return
fabs
(a - b) < MIN_VALUE;
}
void
func()
{
char
temp;
int
i;
for
(i = 0; i < str.length(); i++)
{
if
(str[i] !=
'('
&& str[i] !=
')'
&& str[i] !=
'['
&& str[i] !=
']'
&& str[i] !=
'{'
&& str[i] !=
'}'
)
continue
;
if
(sta.empty())
{
if
(maps[str[i]] > 1)
{
break
;
}
else
{
sta.push(str[i]);
}
}
else
{
temp = sta.top();
if
(maps[str[i]] < 1)
// ([{
{
sta.push(str[i]);
}
else
if
(equ(maps[str[i]], maps[temp] + 1))
// )]}
{
sta.pop();
}
else
{
break
;
}
}
}
if
(i == str.length() && sta.empty())
cout <<
"yes"
<< endl;
else
{
cout <<
"no"
<< endl;
}
}
int
main()
{
int
n;
setMaps();
while
(cin >> n)
{
cin.ignore();
for
(
int
i = 0; i < n; i++)
{
getline(cin, str);
while
(!sta.empty())
sta.pop();
func();
}
}
return
0;
}
/**************************************************************
Problem: 1982
User: morizunzhu
Language: C++
Result: 正确
Time:0 ms
Memory:2044 kb
****************************************************************/