符号配对 (20分)
请编写程序检查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
思路:
因为输入中有/* */这种两个单元的符号,遂考虑一个判断函数,用来将符号转化为数字,左边为正数,右边为负数。
遇到正数符号的时候直接入栈,遇到负数符号的时候,判断currentChar + s.top()是否为零,
为零:出栈
不为零:printError(s.top())
其他情况自行阅读代码。
上代码:
#include <iostream>
#include <cstring>
#include <string>
#include <stack>
#include <map>
using namespace std;
// /**/{}()[]
typedef int Position;
struct CodeStream {
string code;
Position pos = 0;
Position length = 0;
};
map<char, int> symbolVal{
{'(', 1}, {')',-1},
{'[', 2}, {']',-2},
{'{', 3}, {'}',-3},
};
map<int, string> valSymbol{
{1,"("}, {-1,")"},
{2,"["}, {-2,"]"},
{3,"{"}, {-3,"}"},
{4,"/*"},{-4,"*/"}
};
CodeStream& getInput();
int getMark(CodeStream& codeStream);
void printError(int c);
int main() {
auto codeStream = getInput();
stack<int> s;
while (codeStream.pos < codeStream.length) {
const auto currentSymbol = getMark(codeStream);
if (currentSymbol > 0) {
s.push(currentSymbol);
} else if (currentSymbol < 0) {
if (s.empty()) printError(currentSymbol);
if (s.top() + currentSymbol) printError(s.top());
else s.pop();
}
codeStream.pos += 1 + (abs(currentSymbol) == 4);
}
if (!s.empty()) printError(s.top());
cout << "YES" << endl;
return 0;
}
CodeStream& getInput() {
auto rtn = new CodeStream;
char tmpString[1000]{ '\0' };
do {
rtn->code += tmpString;
cin.getline(tmpString, sizeof tmpString);
} while (strcmp(tmpString, ".") != 0);
rtn->length = rtn->code.length();
return *rtn;
}
int getMark(CodeStream& codeStream) {
const auto currentChar = codeStream.code[codeStream.pos];
if (symbolVal.find(currentChar)!=symbolVal.end()) {
return symbolVal[currentChar];
}
if (currentChar == '/' && codeStream.code[codeStream.pos + 1] == '*')
return 4;
if (currentChar == '*' && codeStream.code[codeStream.pos + 1] == '/')
return -4;
return 0;
}
void printError(int c) {
cout << "NO" << endl;
if (c < 0) cout << "?-" << valSymbol[c] << endl;
else cout << valSymbol[c] << "-?" << endl;
exit(0);
}