首页 > 其他分享 >【栈】LeetCode 224. 基本计算器

【栈】LeetCode 224. 基本计算器

时间:2023-01-23 23:33:14浏览次数:66  
标签:addLast ops int nums isEmpty 计算器 cs 224 LeetCode

题目链接

224. 基本计算器

思路

image

代码

class Solution {
    public int calculate(String s) {
        // 存放所有的数字
        Deque<Integer> nums = new ArrayDeque<>();
        // 为了防止第一个数为负数,先往 nums 加个 0
        nums.addLast(0);
        // 将所有的空格去掉
        s = s.replaceAll(" ", "");
        // 存放所有的操作,包括 +/-
        Deque<Character> ops = new ArrayDeque<>();
        int n = s.length();
        char[] cs = s.toCharArray();
        for(int i = 0; i < n; i++){
            char c = cs[i];
            if(c == '('){
                ops.addLast(c);
            }else if(c == ')'){
                // 计算到最近一个左括号为止
                while(!ops.isEmpty()){
                    char op = ops.peekLast();
                    if(op != '('){
                        calc(nums, ops);
                    }else{
                        ops.pollLast();
                        break;
                    }
                }
            }else{
                if(isNum(c)){
                    int u = 0;
                    int j = i;
                    // 将从 i 位置开始后面的连续数字整体取出,加入 nums
                    while(j < n && isNum(cs[j])){
                        u = u * 10 + (int) (cs[j++] - '0');
                    }
                    nums.addLast(u);
                    i = j - 1;
                }else{
                    if(i > 0 && (cs[i - 1] == '(' || cs[i - 1] == '+' || cs[i - 1] == '-')){
                        nums.addLast(0);
                    }
                    // 有一个新操作要入栈时,先把栈内可以算的都算了
                    while(!ops.isEmpty() && ops.peekLast() != '('){
                        calc(nums, ops);
                    }
                    ops.addLast(c);
                }
            }
        }

        while(!ops.isEmpty()){
            calc(nums, ops);
        }

        return nums.peekLast();
    }

    void calc(Deque<Integer> nums, Deque<Character> ops) {
        if(nums.isEmpty() || nums.size() < 2){
            return;
        }
        if(ops.isEmpty()){
            return;
        }

        int b = nums.pollLast(), a = nums.pollLast();
        char op = ops.pollLast();
        nums.addLast(op == '+' ? a + b : a - b);
    }

    boolean isNum(char c) {
        return Character.isDigit(c);
    }
}

标签:addLast,ops,int,nums,isEmpty,计算器,cs,224,LeetCode
From: https://www.cnblogs.com/shixuanliu/p/17065693.html

相关文章

  • 【LeetCode哈希表#1】有效的字母异位词
    有效的字母异位词力扣题目链接(opensnewwindow)给定两个字符串s和t,编写一个函数来判断t是否是s的字母异位词。示例1:输入:s="anagram",t="nagaram"......
  • [LeetCode] 2303. Calculate Amount Paid in Taxes
    Youaregivena 0-indexed 2Dintegerarray brackets where brackets[i]=[upperi,percenti] meansthatthe ith taxbrackethasanupperboundof upperi......
  • leetcode-572-easy
    SubtreeofAnotherTreeGiventherootsoftwobinarytreesrootandsubRoot,returntrueifthereisasubtreeofrootwiththesamestructureandnodevalues......
  • leetcode-559-easy
    MaximumDepthofN-aryTreeGivenan-arytree,finditsmaximumdepth.Themaximumdepthisthenumberofnodesalongthelongestpathfromtherootnodedow......
  • leetcode-543-easy
    DiameterofBinaryTreeGiventherootofabinarytree,returnthelengthofthediameterofthetree.Thediameterofabinarytreeisthelengthofthelon......
  • leetcode-530-easy
    MinimumAbsoluteDifferenceinBSTGiventherootofaBinarySearchTree(BST),returntheminimumabsolutedifferencebetweenthevaluesofanytwodifferent......
  • leetcode-405-easy
    ConvertaNumbertoHexadecimalGivenanintegernum,returnastringrepresentingitshexadecimalrepresentation.Fornegativeintegers,two’scomplementmet......
  • leetcode-501-easy
    FindModeinBinarySearchTreeGiventherootofabinarysearchtree(BST)withduplicates,returnallthemode(s)(i.e.,themostfrequentlyoccurredelemen......
  • LeetCode最长回文子串(/dp)
    原题解题目约束解法解法一#include<iostream>#include<string>#include<vector>usingnamespacestd;classSolution{public:stringlongestPa......
  • LeetCode_单周赛_329
    2544.交替数字和代码1转成字符串,逐个判断classSolution{publicintalternateDigitSum(intn){char[]s=(""+n).toCharArray();intt......