括号匹配
题目:检查一段C语言代码的小括号( )、 中括号 [ ] 和大括号{ } 是否匹配。
输入格式:
在一行中输入一段C语言代码,长度不超过1000个字符(行末以换行符结束)。
输出格式:
第一行输出左括号的数量和右括号的数量,中间以一个空格间隔。
若括号是匹配的,在第二行打印YES,否则打印NO。
输入样例1:
for(int i=0; i<v; i++){ visited[i] = 0; for(int j=0; j<v; j++) scanf("%d",&(g->Adj[i][j])); }
输出样例1:
8 8
YES
输入样例2:
for(int i=0; i<v; i++) a(i]=0;
输出样例2:
2 2
NO
#include <iostream>
#include <stack>
using namespace std;
bool is_left_kuohao(char ch)
{
return ch == '(' || ch == '[' || ch == '{';
}
bool is_right_kuohao(char ch)
{
return ch == ')' || ch == ']' || ch == '}';
}
bool match(char left, char right)
{
return (left == '(' && right == ')') ||
(left == '[' && right == ']') ||
(left == '{' && right == '}');
}
int main()
{
string line;
getline(cin, line);
int left_kuohao_count = 0;
int right_kuohao_count = 0;
for (int i = 0; i < line.length(); i++)
{
if (is_left_kuohao(line[i]))
left_kuohao_count += 1;
if (is_right_kuohao(line[i]))
right_kuohao_count += 1;
}
cout << left_kuohao_count << " "
<< right_kuohao_count << endl;
stack<char> left_kuohaos;
for (int i = 0; i < line.length(); i++)
{
if (is_left_kuohao(line[i]))
left_kuohaos.push(line[i]);
if (is_right_kuohao(line[i]))
{
if (!left_kuohaos.empty() && match(left_kuohaos.top(), line[i]))
left_kuohaos.pop();
else
{
cout << "NO" << endl;
return 0;
}
}
}
if (left_kuohaos.empty())
cout << "YES" << endl;
else
cout << "NO" << endl;
return 0;
}