【LeetCode】224. Basic Calculator


Basic Calculator

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

 

Note: Do not use the eval built-in library function.

 

兩個要點:

1、無括號時,順序執行

2、有括號時,先執行括號中的

兩個棧:

一個存放操作數,每次進棧要注意,如果操作符棧頂元素為'+'/'-',則需要立即計算。

一個存放操作符(包括括號),每次出現')'時,不斷進行出棧計算再進棧,直到彈出'(',說明當前括號內計算完畢。

class Solution {
public:
    int calculate(string s) {
        stack<int> num;
        stack<int> op;
        int i = 0;
        while(i < s.size())
        {
            while(i < s.size() && s[i] == ' ')
                i ++;
            if(i == s.size())
                break;
            if(s[i] == '+' || s[i] == '-' || s[i] == '(')
            {
                op.push(s[i]);
                i ++;   
            }
            else if(s[i] == ')')
            {
                while(op.top() != '(')
                {// calculation within parentheses 
                    int n2 = num.top();
                    num.pop();
                    int n1 = num.top();
                    num.pop();
                    if(op.top() == '+')
                        num.push(n1 + n2);
                    else
                        num.push(n1 - n2);
                    op.pop();
                }
                op.pop();
                while(!op.empty() && op.top() != '(')
                {
                    int n2 = num.top();
                    num.pop();
                    int n1 = num.top();
                    num.pop();
                    if(op.top() == '+')
                        num.push(n1 + n2);
                    else
                        num.push(n1 - n2);
                    op.pop();
                }
                i ++;
            }
            else
            {
                int n = 0;
                while(i < s.size() && s[i] >= '0' && s[i] <= '9')
                {
                    n = n*10 + (s[i]-'0');
                    i ++;
                }
                num.push(n);
                while(!op.empty() && op.top() != '(')
                {
                    int n2 = num.top();
                    num.pop();
                    int n1 = num.top();
                    num.pop();
                    if(op.top() == '+')
                        num.push(n1 + n2);
                    else
                        num.push(n1 - n2);
                    op.pop();
                }
            }
        }
        return num.top();
    }
};


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM