zoukankan      html  css  js  c++  java
  • LeetCode(224) 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. 当遇到)时,将当前()内的表达式计算结果入栈,同时检查操作符栈若有 + 或 - ,立即计算更新两个栈。

    AC代码

    class Solution {
    public:
        int calculate(string s) {
            if (s.empty())
                return 0;
    
            //求出所给表达式的长度
            int len = s.length();
    
            //操作符栈
            stack<char> op_stack;
    
            //操作数栈
            stack<int> num_stack;
            for (int i = 0; i < len; ++i)
            {
                //(1) 跳过空格
                if (s[i] == ' ')
                    continue;
    
                //(2) 操作符入栈
                else if (s[i] == '(' || s[i] == '+' || s[i] == '-')
                {
                    op_stack.push(s[i]);
                    continue;
                }//elif
    
                //(3) 右括号
                else if (s[i] == ')')
                {
                    while (op_stack.top() != '(')
                    {
                        //从数据栈弹出两个操作数
                        int num2 = num_stack.top();
                        num_stack.pop();
                        int num1 = num_stack.top();
                        num_stack.pop();
    
                        //从符号栈,弹出操作符
                        char op = op_stack.top();
                        op_stack.pop();
    
                        if (op == '+')
                            num_stack.push(num1 + num2);
                        else if (op == '-')
                            num_stack.push(num1 - num2);
                    }//while
    
                    //弹出左括号
                    op_stack.pop();     
    
                    //此时查看操作数和操作符栈
                    while (!op_stack.empty() && op_stack.top() != '(')
                    {
                        //从数据栈弹出两个操作数
                        int num2 = num_stack.top();
                        num_stack.pop();
                        int num1 = num_stack.top();
                        num_stack.pop();
    
                        //从符号栈,弹出操作符
                        char op = op_stack.top();
                        op_stack.pop();
    
                        if (op == '+')
                            num_stack.push(num1 + num2);
                        else if (op == '-')
                            num_stack.push(num1 - num2);
                    }//while
                }//elif
                else{
                    int num = 0;
                    while (i < len && isDigit(s[i]))
                    {
                        num = num * 10 + (s[i] - '0');
                        i++;
                    }//while
                    //回退一个字符
                    --i;
                    num_stack.push(num);
    
                    //此时查看操作数和操作符栈
                    while (!op_stack.empty() && op_stack.top() != '(')
                    {
                        //从数据栈弹出两个操作数
                        int num2 = num_stack.top();
                        num_stack.pop();
                        int num1 = num_stack.top();
                        num_stack.pop();
    
                        //从符号栈,弹出操作符
                        char op = op_stack.top();
                        op_stack.pop();
    
                        if (op == '+')
                            num_stack.push(num1 + num2);
                        else if (op == '-')
                            num_stack.push(num1 - num2);
                    }//while
                }       
            }//for
            return num_stack.top();
        }
    
        bool isDigit(char c)
        {
            if (c >= '0' && c <= '9')
                return true;
            else
                return false;
        }
    };
    

    GitHub测试程序源码

  • 相关阅读:
    leetcode 347. Top K Frequent Elements
    581. Shortest Unsorted Continuous Subarray
    leetcode 3. Longest Substring Without Repeating Characters
    leetcode 217. Contains Duplicate、219. Contains Duplicate II、220. Contains Duplicate、287. Find the Duplicate Number 、442. Find All Duplicates in an Array 、448. Find All Numbers Disappeared in an Array
    leetcode 461. Hamming Distance
    leetcode 19. Remove Nth Node From End of List
    leetcode 100. Same Tree、101. Symmetric Tree
    leetcode 171. Excel Sheet Column Number
    leetcode 242. Valid Anagram
    leetcode 326. Power of Three
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214720.html
Copyright © 2011-2022 走看看