LeetCode //C - 150. Evaluate Reverse Polish Notation

150. Evaluate Reverse Polish Notation

You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation.

Evaluate the expression. Return an integer that represents the value of the expression.

Note that:

  • The valid operators are ‘+’, ‘-’, ‘*’, and ‘/’.
  • Each operand may be an integer or another expression.
  • The division between two integers always truncates toward zero.
  • There will not be any division by zero.
  • The input represents a valid arithmetic expression in a reverse polish notation.
  • The answer and all the intermediate calculations can be represented in a 32-bit integer.
     

Example 1:

Input: tokens = [“2”,“1”,“+”,“3”,“*”]
Output: 9
Explanation: ((2 + 1) * 3) = 9

Example 2:

Input: tokens = [“4”,“13”,“5”,“/”,“+”]
Output: 6
Explanation: (4 + (13 / 5)) = 6

Example 3:

Input: tokens = [“10”,“6”,“9”,“3”,“+”,“-11”,““,”/“,””,“17”,“+”,“5”,“+”]
Output: 22
Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22

Constraints:

  • 1 < = t o k e n s . l e n g t h < = 1 0 4 1 <= tokens.length <= 10^4 1<=tokens.length<=104
  • tokens[i] is either an operator: “+”, “-”, “*”, or “/”, or an integer in the range [-200, 200].

From: LeetCode
Link: 150. Evaluate Reverse Polish Notation


Solution:

Ideas:

The core idea behind evaluating RPN expressions is to use a stack data structure. Here’s a step-by-step breakdown of the concept:

1. Initialize an Empty Stack:

  • This stack will be used to keep track of numbers and intermediate results.

2. Iterate Through the Tokens:

  • For each token in the RPN expression:
  • If it’s a number, push it onto the stack.
  • If it’s an operator (like ‘+’, ‘-’, ‘*’, ‘/’), then it means we need to apply this operation to the previous two numbers (operands). These two operands are the top two numbers on our stack.

3. Perform the Operation:

  • Pop the top two numbers from the stack. The order of popping is important. The second number popped is the left operand, and the first number popped is the right operand.
  • Apply the operator to these two numbers.
  • Push the result back onto the stack.
  • Repeat this process for every token in the expression.

4. Final Result:

  • After processing all the tokens, the stack will contain only one number. This number is the result of the RPN expression.
Code:
bool isOperator(char* token) {
    return strcmp(token, "+") == 0 || strcmp(token, "-") == 0 || strcmp(token, "*") == 0 || strcmp(token, "/") == 0;
}

int evalRPN(char ** tokens, int tokensSize) {
    int* stack = (int*)malloc(tokensSize * sizeof(int));
    int stackTop = -1; // Representing an empty stack
    
    for (int i = 0; i < tokensSize; i++) {
        if (isOperator(tokens[i])) {
            // Pop two numbers from the stack
            int b = stack[stackTop--];
            int a = stack[stackTop--];
            
            // Apply the operator and push the result onto the stack
            switch(tokens[i][0]) {
                case '+': 
                    stack[++stackTop] = a + b; 
                    break;
                case '-': 
                    stack[++stackTop] = a - b; 
                    break;
                case '*': 
                    stack[++stackTop] = a * b; 
                    break;
                case '/': 
                    stack[++stackTop] = a / b; 
                    break;
            }
        } else {
            // Convert the token to an integer and push it onto the stack
            stack[++stackTop] = atoi(tokens[i]);
        }
    }
    
    // The result is now on top of the stack
    int result = stack[stackTop];
    free(stack);
    
    return result;
}

你可能感兴趣的:(LeetCode,leetcode,c语言,算法)