C語言 符號配對 (20分)

符號配對 (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);
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章