【Leetcode】Basic Calculator

题目链接:https://leetcode.com/problems/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.

思路:

用栈保存操作数、操作符,要注意处理右括号的情况。

算法:

    public int calculate(String s) {
        Stack<String> operator = new Stack<String>();
        Stack<Integer> nums = new Stack<Integer>();
        s = s.replace(" ", "");
        int curNum = 0; // 连续字符都是数字要组合成一个数
        for (int i = 0; i < s.length(); i++) {
            char op = s.charAt(i);
            if (Character.isDigit(op)) { // 当前是数字
                curNum = Integer.parseInt(op + "");
                while (i + 1 < s.length() && Character.isDigit(s.charAt(i + 1))) { // 后继字符也是数字,组合成一个数
                    char nextNum = s.charAt(i + 1);
                    curNum = curNum * 10 + Integer.parseInt(nextNum + "");
                    i++;
                }// 一个操作数处理完
                if (!operator.isEmpty()
                        && nums.size() >= 1
                        && (operator.peek().equals("+") || operator.peek()
                                .equals("-"))) { // 若操作数栈有操作数,且
                                                    // 操作符栈有+/-,则将当前数和栈中的数做相应处理
                    String tmp = operator.pop();
                    if (tmp.equals("-")) {
                        int first = nums.pop();
                        nums.push(first - curNum);
                    } else {
                        nums.push(nums.pop() + curNum);
                    }
                } else {
                    nums.push(curNum);
                }
            } else { // 当前字符是操作符
                if (op == ‘+‘ || op == ‘-‘ || op == ‘(‘) {
                    operator.push(op + "");
                } else if (op == ‘)‘) {
                    if (operator.peek().equals("(")) { // 若括号消除,则要处理左括号前面的运算,即处理
                                                        // 1+(4)中+的计算
                        operator.pop();
                        if (!operator.isEmpty()
                                && nums.size() >= 2
                                && (operator.peek().equals("+") || operator
                                        .peek().equals("-"))) {
                            String tmp = operator.pop();
                            if (tmp.equals("-")) {
                                int first = nums.pop();
                                int second = nums.pop();
                                nums.push(second - first);
                            } else {
                                nums.push(nums.pop() + nums.pop());
                            }
                        }
                    } else {
                        operator.push(")");
                    }
                }
            }
        }
        return nums.pop();
    }
时间: 2024-12-29 05:36:48

【Leetcode】Basic Calculator的相关文章

【LeetCode】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 expressio

【Leetcode】Basic Calculator II

题目链接:https://leetcode.com/problems/basic-calculator-ii/ 题目: Implement a basic calculator to evaluate a simple expression string. The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division s

【LeetCode】数学(共106题)

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica } [2]Add Two Numbers [7]Reverse Integer [8]String to Integer (atoi) [9]Palindrome Number [12]Integer to Roman [13]Roman to Integer [29]Divide Two Integers [43]Multiply Strings [50]Pow(x,

【LeetCode】栈 stack(共40题)

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica } [20]Valid Parentheses [42]Trapping Rain Water [71]Simplify Path [84]Largest Rectangle in Histogram [85]Maximal Rectangle [94]Binary Tree Inorder Traversal [103]Binary Tree Zigzag Level

【LeetCode】字符串 string(共112题)

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica } [3]Longest Substring Without Repeating Characters [5]Longest Palindromic Substring [6]ZigZag Conversion [8]String to Integer (atoi) [10]Regular Expression Matching [12]Integer to Roman

【LeetCode】哈希表 hash_table(共88题)

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica } [1]Two Sum (2018年11月9日,k-sum专题,算法群衍生题) 给了一个数组 nums, 和一个 target 数字,要求返回一个下标的 pair, 使得这两个元素相加等于 target . 题解:我这次最大范围的优化代码, hash-table + one pass,时间复杂度 O(N),空间复杂度 O(N).重点在于动态找,一边生成hash-tabl

【leetcode】Generate Parentheses

题目: 给定整数n,返回n对匹配的小括号字符串数组. For example, given n = 3, a solution set is: "((()))", "(()())", "(())()", "()(())", "()()()" 分析: 这种问题的模式是:1)问题的解有多个 ,2)每个解都是由多个有效的 "步骤" 组成的,3)变更以有解的某个或某些"步骤"

【LeetCode】Implement strStr()

Implement strStr() Implement strStr(). Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack. 标准KMP算法.可参考下文. http://blog.csdn.net/yaochunnian/article/details/7059486 核心思想在于求出模式串前缀与后缀中重复部分,将重复信息保存在n

【LeetCode】Add Two Numbers

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. Input: (2 -> 4 -> 3) + (5 -> 6 ->