• Algorithms practice:Basic Calculator 224


    224. Basic Calculator

    Description

    Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.

    Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().
    Constraints:

    1 <= s.length <= 3 * 105
    s consists of digits, ‘+’, ‘-’, ‘(’, ‘)’, and ’ '.
    s represents a valid expression.
    ‘+’ is not used as a unary operation (i.e., “+1” and “+(2 + 3)” is invalid).
    ‘-’ could be used as a unary operation (i.e., “-1” and “-(2 + 3)” is valid).
    There will be no two consecutive operators in the input.
    Every number and running calculation will fit in a signed 32-bit integer.

    Example

    Example 1:

    Input: s = “1 + 1”
    Output: 2
    Example 2:

    Input: s = " 2-1 + 2 "
    Output: 3
    Example 3:

    Input: s = “(1+(4+5+2)-3)+(6+8)”
    Output: 23

    Analysis

    code

    class Solution {
    public:
        int calculate(string s) {
            int i=0;
            int sign=1;
            int result=0;
            stack<int> numStack;
            stack<int> operatorStack;
            while(i<s.size())
            {
                if(s[i] =='(')
                {
                    numStack.push(result);
                    operatorStack.push(sign);
                    result=0;
                    sign=1;
                }
                else if(s[i] ==')')
                {
                    int tempNum=numStack.top();
                    int tempoper = operatorStack.top();
                    result=tempNum+ result * tempoper;
                    numStack.pop();
                    operatorStack.pop();
                }
                else if(s[i] =='+')
                {
                    sign=1;
                }
                else if(s[i] =='-')
                {
                    sign=-1;
                }
                else if(s[i] ==' ')
                {
                    
                }
                else
                {
                    long num=0;
                    while((s[i]>='0' || s[i]<=9) && i<s.size())
                    {
                        num = num*10 + s[i] - '0';
                        i++;
                    }
                    result = result + num*sign;
                    i--;
                }
                i++;
            }
            return result;
        }
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53

    Oral process of solving problems

    see this youtube Code with Jess - Leetcode #224 Basic Calculator

    this problem is to implement a basic calculator to evaluate a simple expression string, so the input is going to be a string. the expression string may contain open parenthesis, closing parentheses, plus sign, minus sign, non-negative integers, and empty spaces. so let’s take a look at an example. mathematically how it works is we calculate from left to right. but if there is a parenthesis, we calculate whatever is inside the parenthesis first, then the formula outside the parenthesis.

    my approach is to go through the string character by character from left to right and use a stack to save the previous result. when we see an open parenthesis and reach a closing parenthesis, we wrap this result inside and pop whatever is in the stack, then add them together and keep moving to the right side as we calculate.

    2 +(1+(4+5+2) -3) + (6+8)
    sum=2

    so we start from here at this time. sum is 2.

    注释:
    下面公式中加租斜体代表指针当前指向的char
    在这里插入图片描述

    2 + ( 1+(4+5+2) -3) + (6+8)

    numStack: [2]
    operatorStack: [ + ]
    sum =0 
    
    • 1
    • 2
    • 3

    we move along and see open parenthesis. so we add the current sum and the operation outside the parenthesis which is plus. then we reset the sum to zero.

    2 +(1+(4+5+2) -3) + (6+8)

    numStack: [2]
    operatorStack: [ + ]
    sum = 1
    
    • 1
    • 2
    • 3

    we calculate whatever it is inside this parenthesis here. we have sum equals to 1.

    2 +(1+ ( 4+5+2) -3) + (6+8)

    numStack: [2, 1 ]
    operatorStack: [ +,+ ]
    sum =0
    
    • 1
    • 2
    • 3

    we move along and see another open parenthesis that’s when we save the current sum to the stack and the operator pushes plus. we reset the sum to 0.

    2 +(1+(4+5+2) -3) + (6+8)

    numStack: [2, 1 ]
    operatorStack: [ +,+ ]
    sum =11
    
    • 1
    • 2
    • 3

    I move inside of the parenthesis. we have 4 and then we have 4 plus 5 which is 9. we’re moving along. 9 plus 2 which is 11.

    2 +(1+(4+5+2 ) -3) + (6+8)

    numStack: [2] pop 1
    operatorStack: [ + ] pop +
    sum =12
    
    • 1
    • 2
    • 3

    we see a closing parenthesis that’s when we start popping the stack.we see inside a stack we have 1 and we have plus that makes our sum 12.

    2 +(1+(4+5+2) -3) + (6+8)

    numStack: [2]  
    operatorStack: [ + ]  
    sum =9
    
    • 1
    • 2
    • 3

    then we’ll move along with the minus three. so sum minus three is 9.

    2 +(1+(4+5+2) -3 ) + (6+8)

    numStack: []  pop 2
    operatorStack: [ ]  pop +
    sum =9+2 =11
    
    • 1
    • 2
    • 3

    then we see another closing parenthesis that’s when we pop this stack again. so 2 plus 9 is 11. now the stack is empty.

    2 +(1+(4+5+2) -3) + ( 6+8)

    numStack: [11]  
    operatorStack: [+ ]  
    sum =0
    
    • 1
    • 2
    • 3

    we move along and see another open parenthesis. we saved the current sum and the operator then reset the sum.

    2 +(1+(4+5+2) -3) + (6+8)

    sum =6+8 =14
    
    • 1
    numStack: [ ]  pop 11
    operatorStack: [ ]  pop +
    sum =14 +11 =25 
    
    • 1
    • 2
    • 3

    now we see 6 plus 8 is 14.

    2 +(1+(4+5+2) -3) + (6+8 )

    we see a closing parenthesis that’s when we pop this stack so now sum is 14 plus 11 which is 25. now stack should be empty. so 25 should be our final result.

    the time complexity of this solution should be O(n). because we go through each character of the string once. now let’s write the code since. in this problem, we’re only going to have a plus sign and a minus sign. for saving the sign, I’m simply just going to use an integer. I will initialize it to 1 so when it’s minus we just change the sign to negative 1. we will also need a sum to initialize it to zero, also a stack to iterate throughout this string. I will use a loop. so for this problem, we have five scenarios as different kinds of input. we can have a number, we can have a plus sign we have a minus sign, or open parenthesis and closed parenthesis. otherwise, we will just ignore the digit such as a space.

    在这里插入图片描述

    first of all, I’m going to check if the current position is a number. so now the number might be one digit like 9 or it can be more than one digit like 999. so we need to read through the entire number. so I’ll use a while loop to keep checking the current digit until the next digit is not a number and add to this number as the pointer moves. after we get a complete number we will grab the sign and update this sum.

    or xxx -999, sum =sum + (-1)*999 => sum =sum -999
    在这里插入图片描述

    so if it’s something minus 999, will have the sum equal to sum plus the sign which will be negative 1 times the 999, which is equivalent to sum equals to sum minus 999. by this time our i is pointing to the digit after the number and here in the for a loop were updated i again. we need to reset i back one space that’s a scenario if we’re looking at a number. so if the current digit is a plus sign then we need to update the sign to a positive one. similarly, if the current character is a minus sign then we’ll update the sign to a negative one.

    now let’s take a look at the scenario when the current character is open parenthesis as we said in that case we’re going to save the operator and the current sum into the stack and set sum to zero, sign to one.

    in our last scenario which is when we see a closing parenthesis. when we see a closing parenthesis, we pop the previous sum and the previous sign and do the operation with the current sum. that should cover all our scenarios.

    so after this full loop, the sum should be the final result that we want so we return the sum. so let’s take a look at this problem from the beginning, we have the default sign to 1. we have a sum initialized to 0, and a stack. we go through each character in the string with this number then while a current digit is a number and i is less than the length of the string. we add this current digit to the current number and update the i. when we get a complete number, we update the sum and reset i to one digit back. otherwise, if it’s a plus sign now though the sign is one. if the sign is a minus sign then we update a sign to a negative one. if we see an open parenthesis, we push our current sum to the stack, and push the current sign to the stack, set the sum to zero, sign to one as default. last but not least when we see a closing parenthesis, we pop the sign from the stack and update our current sum, then add our current sum to the previous sum. after everything, we’re returning the son so that should be it let’s run it.

    words

    参考
    Basic Calculator

  • 相关阅读:
    Java实现简单的通讯录
    深度学习的进展,产业化,规模化、数据化
    树莓派 Pico RP2040 MicroPython 编程 - 软件安装及设置
    Leetcode | 560. 和为 K 的子数组
    【Java】反射 之 获取继承关系
    kubernetes资源对象介绍及常用命令(二)
    思维导图软件 ConceptDraw MINDMAP mac中文特色介绍
    Spring系列文章:面向切面编程AOP
    运营商认证API在Java、Python、PHP中的使用教程
    全连接=可编程!玻色量子成功研制光量子测控一体机——“量枢”
  • 原文地址:https://blog.csdn.net/fuyouzhiyi/article/details/126806451