[Leetcode] 224. Basic-calculator (stack) [difficult]

link

https://leetcode-cn.com/problems/basic-calculator/

time consuming

Problem solving: 19 min
Problem solving: 12 min

Title

Implement a basic calculator to calculate the value of a simple string expression s.

Ideas

There are only addition and subtraction and parentheses. Open the parentheses completely and the calculation result will not change, so you only need to deal with the actual sign before each number, and add these numbers to the result according to the actual sign.

Because the brackets are included, the stack is used to record the symbols before the brackets. When encountering a'+', the current symbol is the top symbol of the stack. When encountering a'-', the current symbol is the opposite symbol of the top symbol of the stack. The actual symbol is pushed onto the stack, and the symbol at the top of the stack is popped out when encountering a')'. When encountering a number, the number is read out and multiplied by the current symbol and added to the result.

Time complexity: O (n) O(n)O ( n )

AC code

class Solution {
    
    
public:
    int calculate(string s) {
    
    
        int n = s.size();
        stack<int> st;
        st.push(1);
        int sign = 1;
        int ans = 0;
        for(int i = 0; i < n; ++i) {
    
    
            if(s[i] == ' ') continue;
            else if(s[i] == '+') {
    
    
                sign = st.top();
            }
            else if(s[i] == '-') {
    
    
                sign = -st.top();
            }
            else if(s[i] == '(') {
    
    
                st.push(sign);
            }
            else if(s[i] == ')') {
    
    
                st.pop();
            }
            else {
    
    
                int num = 0;
                while(s[i] >= '0' && s[i] <= '9') {
    
    
                    num = num*10 + (s[i]-'0');
                    i++;
                }
                i--;
                ans += sign*num;
            }
        }
        return ans;
    }
};

Guess you like

Origin blog.csdn.net/Krone_/article/details/114644165