有括号的运算,只有加减运算。很明显本题只考察括号匹配没有再加入乘除,否则就真是半个计算器的工程了。由于我是先写了计算器二式,所以本题也想用一次扫描就出结果。但由于有括号要考虑出栈,要考虑单个括号括的数、左右括号中有算式的、连续括号的,所以边界判断很多,写了3种情况,一个个if把程序搞得很臃肿,自我感觉写的不好。
其实本题我觉得用2n时间度可能更好,第一遍扫就干托括号的事,第二遍再扫就干计算的事,逻辑就更清楚,应该也不慢。
臃肿程序如下,ac12ms:
int calculate(char* s) {
int result = 0;
int n = 10240;
int numstack[n];
char operastack[n];
memset(numstack, 0, sizeof(int) * n);
memset(operastack, 0, sizeof(char) * n);
char *sp = s;
char *nums = "1234567890";
char *operas = "(+-";
char *plusMinus = "+-";
char left = '(', right = ')';
int num = 0;
int indexn = 0, indexo = 0;
bool isKuohao = false;
while (*sp != '\0') {
if (strchr(nums, *sp)) { //操作数入栈
while (strchr(nums, *sp) && *sp != '\0') {
num = num * 10 + *sp - '0';
sp++;
}
numstack[indexn] = num;
indexn++;
if (indexn > 1 && strchr(plusMinus, operastack[indexo - 1])) { //操作数大于1且操作栈最后一个是可运算符则直接运算
int temp = 0;
if (operastack[indexo - 1] == '+')
temp = numstack[indexn - 1] + numstack[indexn - 2];
else
temp = numstack[indexn - 2] - numstack[indexn - 1];
numstack[indexn - 2] = temp;
indexn--;
indexo--;
}
}
if (strchr(operas, *sp) && *sp != '\0') { //操作符入栈
num = 0;
operastack[indexo] = *sp;
indexo++;
if (indexo > 1 && strchr(plusMinus, operastack[indexo - 1]) && strchr(plusMinus, operastack[indexo - 2])) {
//连续两个为可操作符时则计算前一个
int temp = 0;
if (operastack[indexo - 2] == '+')
temp = numstack[indexn - 1] + numstack[indexn - 2];
else
temp = numstack[indexn - 2] - numstack[indexn - 1];
numstack[indexn - 2] = temp;
indexn--;
operastack[indexo - 2] = operastack[indexo - 1];
indexo--;
}
}
if (*sp == right) { //遇到右括号,则退栈运算
if (operastack[indexo - 1] == '(')
indexo--;
else
{
int tempn = 0;
char tempo = operastack[indexo - 1];
if (tempo == '+')
tempn = numstack[indexn - 2] + numstack[indexn - 1];
else
tempn = numstack[indexn - 2] - numstack[indexn - 1];
numstack[indexn - 2] = tempn;
indexn--;
indexo -= 2;
}
isKuohao = true;
}
sp++;
}
if (isKuohao && indexo > 0) {
char tempo = operastack[0];
if (tempo == '+')
numstack[0] = numstack[0] + numstack[1];
else if (tempo == '-')
numstack[0] = numstack[0] - numstack[1];
}
result = numstack[0];
return result;
}