请编写程序检查C语言源程序中下列符号是否配对:/*
与*/
、(
与)
、[
与]
、{
与}
。
输入格式:
输入为一个C语言源程序。当读到某一行中只有一个句点.和一个回车的时候,标志着输入结束。程序中需要检查配对的符号不超过100个。
输出格式:
首先,如果所有符号配对正确,则在第一行中输出YES
,否则输出NO
。然后在第二行中指出第一个不配对的符号:如果缺少左符号,则输出?-右符号
;如果缺少右符号,则输出左符号-?
。
输入样例1:
void test()
{
int i, A[10];
for (i=0; i<10; i++) /*/
A[i] = i;
}
.
输出样例1:
NO
/*-?
输入样例2:
void test()
{
int i, A[10];
for (i=0; i<10; i++) /**/
A[i] = i;
}]
.
输出样例2:
NO
?-]
输入样例3:
void test()
{
int i
double A[10];
for (i=0; i<10; i++) /**/
A[i] = 0.1*i;
}
.
输出样例3:
YES
18分测试点3有点问题
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <map>
#include <set>
#include <cmath>
#include <string>
#include <queue>
#include <stack>
#include <list>
//#include <regex>
//#include <functional>
using namespace std;
int main() {
stack<char>st;
string a;
while (getline(cin, a) && a != ".") {
for (int i = 0; i < a.size(); ++i) {
if (a[i] == '(' || a[i] == '[' || a[i] == '{' || a[i] == '/' && a[i + 1] == '*') {
st.push(a[i]);
if (a[i] == '/')++i;
}
else if (a[i] == ')') {
if (!st.empty() && st.top() == '(')
st.pop();
else {
cout << "NO" << endl;
if (st.empty())
cout << "?-)";
else {
if (st.top() == '/')
cout << "/*-?";
else
cout << st.top() << "-?";
}
exit(0);
}
}
else if (a[i] == ']') {
if (!st.empty() && st.top() == '[')
st.pop();
else {
cout << "NO" << endl;
if (st.empty())
cout << "?-]";
else {
if (st.top() == '/')
cout << "/*-?";
else
cout << st.top() << "-?";
}
exit(0);
}
}
else if (a[i] == '}') {
if (!st.empty() && st.top() == '{')
st.pop();
else {
cout << "NO" << endl;
if (st.empty())
cout << "NO" << "?-}";
else {
if (st.top() == '/')
cout << "/*-?";
else
cout << st.top() << "-?";
}
exit(0);
}
}
else if (a[i] == '*' && a[++i] == '/') {
if (!st.empty() && st.top() == '/')
st.pop();
else {
cout << "NO" << endl;
if (st.empty())
cout << "?-*/";
else
cout << st.top() << "-?";
exit(0);
}
}
}
}
if (st.empty())
cout << "YES";
else {
cout << "NO" << endl;
if (st.top() == '/')
cout << "/*-?";
else
cout << st.top() << "-?";
}
return 0;
}