標籤:leetcode java stack basiccalculator
題目:
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 .
You may assume that the given expression is always valid.
Some examples:
"1 + 1" = 2" 2-1 + 2 " = 3"(1+(4+5+2)-3)+(6+8)" = 23
解答:
對應這類題型通用的做法是轉成尾碼運算式,然後根據逆波蘭的計算方法進行計算。但這題比較特殊,因為它只有加減,我們可以通過化簡括弧進行計算,比如“1-(2-(4-6)+5)+3”
在這個運算式中,總共有1 2 4 6 5 3這幾個數字,我們只要弄清楚這些數位最終符號是什麼,最終符號取決於數字前面的符號與數字前面所有左括弧前面的那個符號的成績,比如2:+1*(-1) 4:+1*(-1)*(-1) 5:+1*(-1)*(-1) 知道這個就應該看得懂代碼了
代碼:
public static int calculate(String s) { char[] array=s.toCharArray(); Stack<Integer> stack=new Stack<>(); int result=0; int sign=1; stack.push(1); for(int i=0;i<array.length;i++) { if(Character.isDigit(array[i])) { int num=array[i]-'0'; int j=i+1; while(j<array.length&&Character.isDigit(array[j])) { num=10*num+array[j]-'0'; j++; } result+=sign*stack.peek()*num; i=j-1;//j前面等於i+1 } else if(array[i]=='+') sign=1; else if(array[i]=='-') sign=-1; else if(array[i]=='(')//記錄左括弧之前的那個符號,因為它會影響括弧裡面的所有運算子 { stack.push(sign*stack.peek()); sign=1; } else if(array[i]==')')//保證之前左括弧來的時候壓入棧的那個符號不會影響後面那些不在括弧中的運算 stack.pop(); else {;//空格什麼的就不操作} } return result; }
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
LeetCode224 BasicCalculator java題解