LeetCode224 BasicCalculator java題解

來源:互聯網
上載者:User

標籤: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題解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.