[LeetCode ] Basic Calculator
阿新 • • 發佈:2019-02-05
Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open
(
and closing parentheses)
, the plus+
or minus sign-
, non-negative integers and empty spaces .
Example 1:
Input: "1 + 1" Output: 2
Example 2:
Input: " 2-1 + 2 " Output: 3
Example 3:
Input: "(1+(4+5+2)-3)+(6+8)" Output: 23
Note:
- You may assume that the given expression is always valid.
- Do not use the
eval
built-in library function
題意:給出一個只有+-()和非負數的合法表示式,計算這個表示式的值。
思路:大體思路是每次遇到的如果不是),就入棧,遇到),執行出棧操作,直到遇到(,出棧過程中結算這個括號裡的表示式的值,然後把這個值在入棧,寫起來細節還是挺多的。
C程式碼:
int calculate(char* s) { int i,len,top,j; long long stack[100005],temp1,temp2,res; const long long op1 = (long long)INT_MAX + 1,op2 = op1 + 1,op3 = op2 + 1; res = top = 0; len = strlen(s); for(i = 0; i < len; i++) { if(s[i] == '(') { stack[top++] = op3; } else if(s[i] == '+') { stack[top++] = op2; } else if(s[i] == '-') { stack[top++] = op1; } else if(s[i] >= '0' && s[i] <= '9') { temp1 = 0; for(j = i; s[j] >= '0' && s[j] <= '9'; j++) { temp1 = temp1 * 10 + s[j] - '0'; } stack[top++] = temp1; i = j - 1; } else if(s[i] == ')') { temp1 = 0; temp2 = 0; top--; while(stack[top] != op3) { if(stack[top] < op1) { temp1 = stack[top]; } else { if(stack[top] == op1) temp2 -= temp1; else if(stack[top] == op2) temp2 += temp1; } top--; } stack[top++] = temp2 + temp1; } } int flag = 1; for(i = 0; i < top; i++) { if(stack[i] == op2) flag = 1; else if(stack[i] == op1) flag = -1; else res += flag * stack[i]; } return res; }