uva 327 - Evaluating Simple C Expressions

我的做法没有涉及什么语法树,主要是字符串处理,水平略搓写的有点麻烦,题目说忽略空格,youcase比如 a++有可能是a  +  +,导致WA,后来加上了预处理去掉所有空格才AC。

 

#include<stdio.h>
#include<string.h>

char tmpStr[200];
char expr[200];
int appeared[26];
int plus[26];
int minus[26];
char afterExp[200];
int val;

void print() {
	printf("Expression: %s\n", tmpStr);
	printf("    value = %d\n", val);
	int j;
	for (j = 0; j < 26; j++) {
		if (appeared[j]) {
			char ch = j + 'a';
			int value = j + 1;
			if (plus[j] != 0)
				value++;
			if (minus[j] != 0)
				value--;
			printf("    %c = %d\n", ch, value);
		}
	}

}

void init() {
	val = 0;
	int i;
	for (i = 0; i < 26; i++) {
		appeared[i] = 0;
		plus[i] = 0;
		minus[i] = 0;
	}
}

void evaluateAndPrint() {
	init();
	int len = strlen(expr);
	int idx = 0;
	int i;
	for (i = 0; i < len; i++) {
		if (expr[i] >= 'a' && expr[i] <= 'z') {
			appeared[expr[i] - 'a'] = 1;
			afterExp[idx++] = expr[i];
			if (i - 2 >= 0 && expr[i - 1] == '+' && expr[i - 2] == '+')
				plus[expr[i] - 'a'] = -1;
			if (i - 2 >= 0 && expr[i - 1] == '-' && expr[i - 2] == '-')
				minus[expr[i] - 'a'] = -1;
			if (i + 2 < len && expr[i + 1] == '+' && expr[i + 2] == '+')
				plus[expr[i] - 'a'] = 1;
			if (i + 2 < len && expr[i + 1] == '-' && expr[i + 2] == '-')
				minus[expr[i] - 'a'] = 1;
		} else if (expr[i] == '+' || expr[i] == '-') {
			if (i > 0 && i < len - 1 && expr[i - 1] != expr[i]
					&& expr[i] != expr[i + 1])
				afterExp[idx++] = expr[i];
		}

	}
	afterExp[idx] = 0;

	int flag = 1;
	for (i = 0; i < idx; i++) {
		if (afterExp[i] >= 'a' && afterExp[i] <= 'z') {
			int tmp = afterExp[i] - 'a' + 1;
			if (plus[afterExp[i] - 'a'] == -1)
				tmp++;
			if (minus[afterExp[i] - 'a'] == -1)
				tmp--;

			if (flag)
				val += tmp;
			else
				val -= tmp;

		} else if (afterExp[i] == '-')
			flag = 0;
		else if (afterExp[i] == '+')
			flag = 1;
	}

	print();

}

int main() {
	while (gets(tmpStr)) {
		int i;
		int idx = 0;
		for (i = 0; i < strlen(tmpStr); i++) {
			if ((tmpStr[i] >= 'a' && tmpStr[i] <= 'z') || tmpStr[i] == '+'
					|| tmpStr[i] == '-')
				expr[idx++] = tmpStr[i];
		}
		expr[idx] = 0;

		evaluateAndPrint();
	}
	return 0;
}

 

你可能感兴趣的:(uva 327 - Evaluating Simple C Expressions)