LeetCode-772. Basic Calculator III

772. Basic Calculator IIILevel up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.https://leetcode.com/problems/basic-calculator-iii/

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 .

The expression string contains only non-negative integers, +, -, *, / operators , open ( and closing parentheses ) and empty spaces . The integer division should truncate toward zero.

You may assume that the given expression is always valid. All intermediate results will be in the range of [-2147483648, 2147483647].

Some examples:

  1. "1 + 1" = 2

  2. " 6-4 / 2 " = 4

  3. "2*(5+5*2)/3+(6/2+8)" = 21

  4. "(2+6* 3+5- (3*14/7+2)*5)+3"=-12

【C++】

class Solution {
public:
    int calculate(string s) {
        if (s == nullptr || s.length() == 0) {return 0;}
        char sign = '+';
        int num = 0, res = 0, len = s.length();
        stack<int> stack;
        for (int i = 0; i < len; i++) {
            char c = s[i];
            if (isdigit(c)) {num = num * 10 + c - '0';}
            if (!isdigit(c) && c != ' ' || i == len - 1) {
                if (c == '(') {
                    int j = i, int count = 0;
                    for (; i < len; i++) {
                        if (s[i] == '(') {count++;}
                        if (s[i] == ')') {count--;}
                        if (count == 0) {break;}
                    }
                    num = calculate(s.substr(j + 1, i - j - 1));
                }
                switch (sign) {
                    case '+': stack.push(num);
                    case '-': stack.push(-1 * num);
                    case '*': int a = stack.top(); stack.pop(); stack.push(a * cal);
                    case '/': int a = stack.top(); stack.pop(); stack.push(a / cal);;
                }
                num = 0;
                sign = c; //before next number
            }
        }
        while (!ns.empty()) {
            res += stack.top();
            stack.pop();
        }
        return res;
    }
}

【Java】

import java.util.*
class Solution {
    public int calculate(String s) {
        if(s == null || s.length() == 0) {return 0;}
        char sign = '+';
        int num = 0;
        int res = 0;
        Stack<Integer> stack = new Stack<>();
        int len = s.length();
        for (int i = 0; i < len; i++) {
            char c = s.charAt(i);
            if (Character.isDigit(c)) {num = num * 10 + c - '0';}
            if (!Character.isDigit(c) && c != ' ' || i == len - 1) {
                if (c == '(') {
                    int j = i, int count = 0;
                    for (; i < len; i++) {
                        if (s.charAt(i) == '(') {count++;}
                        if (s.charAt(i) == ')') {count--;}
                        if (count == 0) {break;}
                    }
                    num = calculate(s.substring(j + 1, i));
                }
                switch (sign) {
                    case '+': stack.push(num);
                    case '-': stack.push(-num);
                    case '*': stack.push(stack.pop() * num);
                    case '/': stack.push(stack.pop() / num);
                }
                num = 0;
                sign = c; //before next number
            }
        }
        for (int val: stack) {res += val;}
        return res;
    }
}

another

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.Map;

public class Solution {
    /**
     * @param s: the given expression
     * @return: the result of expression
     */
    public int calculate(String s) {
        // Write your code here
        Map<Character, Integer> prio = new HashMap<>();
        prio.put('(', 1);
        prio.put('+', 2);
        prio.put('-', 2);
        prio.put('*', 3);
        prio.put('/', 3);
        Deque<Character> ops = new ArrayDeque<>();
        Deque<Long> stack = new ArrayDeque<>();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (ch == ' ') {continue;}
            if (ch == '(') {
                ops.push('(');
            } else if (ch == ')') {
                while (ops.peek() != '(') {calc(stack, ops);}
                ops.pop();
            } else if (Character.isDigit(ch)) {
                int j = i;
                while (j < s.length() && Character.isDigit(s.charAt(j))) {
                    j++;
                }
                long num = Long.parseLong(s.substring(i, j));
                stack.push(num);
                i = j - 1;
            } else {
                while (!ops.isEmpty() && prio.get(ops.peek()) >= prio.get(ch)) {
                    calc(stack, ops);
                }
                ops.push(ch);
            }
        }
        while (stack.size() > 1) {calc(stack, ops);}
		long res = stack.peek();
        return (int) res;    
    }
    
    private void calc(Deque<Long> stack, Deque<Character> ops) {
        long n2 = stack.pop(), n1 = stack.pop();
        switch (ops.pop()) {
            case '+': stack.push(n1 + n2); break;
            case '-': stack.push(n1 - n2); break;
            case '*': stack.push(n1 * n2); break;
            case '/': stack.push(n1 / n2); break;
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: 好的,我来用中文回复这个链接:https://leetcode-cn.com/tag/dynamic-programming/ 这个链接是 LeetCode 上关于动态规划的题目集合。动态规划是一种常用的算法思想,可以用来解决很多实际问题,比如最长公共子序列、背包问题、最短路径等等。在 LeetCode 上,动态规划也是一个非常重要的题型,很多题目都需要用到动态规划的思想来解决。 这个链接里包含了很多关于动态规划的题目,按照难度从简单到困难排列。每个题目都有详细的题目描述、输入输出样例、题目解析和代码实现等内容,非常适合想要学习动态规划算法的人来练习和提高自己的能力。 总之,这个链接是一个非常好的学习动态规划算法的资源,建议大家多多利用。 ### 回答2: 动态规划是一种算法思想,通常用于优化具有重叠子问题和最优子结构性质的问题。由于其成熟的数学理论和强大的实用效果,动态规划在计算机科学、数学、经济学、管理学等领域均有重要应用。 在计算机科学领域,动态规划常用于解决最优化问题,如背包问题、图像处理、语音识别、自然语言处理等。同时,在计算机网络和分布式系统中,动态规划也广泛应用于各种优化算法中,如链路优化、路由算法、网络流量控制等。 对于算法领域的程序员而言,动态规划是一种必要的技能和知识点。在LeetCode这样的程序员平台上,题目分类和标签设置十分细致和方便,方便程序员查找并深入学习不同类型的算法LeetCode的动态规划标签下的题目涵盖了各种难度级别和场景的问题。从简单的斐波那契数列、迷宫问题到可以用于实际应用的背包问题、最长公共子序列等,难度不断递进且话题丰富,有助于开发人员掌握动态规划的实际应用技能和抽象思维模式。 因此,深入LeetCode动态规划分类下的题目学习和练习,对于程序员的职业发展和技能提升有着重要的意义。 ### 回答3: 动态规划是一种常见的算法思想,它通过将问题拆分成子问题的方式进行求解。在LeetCode中,动态规划标签涵盖了众多经典和优美的算法问题,例如斐波那契数列、矩阵链乘法、背包问题等。 动态规划的核心思想是“记忆化搜索”,即将中间状态保存下来,避免重复计算。通常情况下,我们会使用一张二维表来记录状态转移过程中的中间值,例如动态规划求解斐波那契数列问题时,就可以定义一个二维数组f[i][j],代表第i项斐波那契数列中,第j个元素的值。 在LeetCode中,动态规划标签下有众多难度不同的问题。例如,经典的“爬楼梯”问题,要求我们计算到n级楼梯的方案数。这个问题的解法非常简单,只需要维护一个长度为n的数组,记录到达每一级楼梯的方案数即可。类似的问题还有“零钱兑换”、“乘积最大子数组”、“通配符匹配”等,它们都采用了类似的动态规划思想,通过拆分问题、保存中间状态来求解问题。 需要注意的是,动态规划算法并不是万能的,它虽然可以处理众多经典问题,但在某些场景下并不适用。例如,某些问题的状态转移过程比较复杂,或者状态转移方程中存在多个参数,这些情况下使用动态规划算法可能会变得比较麻烦。此外,动态规划算法也存在一些常见误区,例如错用贪心思想、未考虑边界情况等。 总之,掌握动态规划算法对于LeetCode的学习和解题都非常重要。除了刷题以外,我们还可以通过阅读经典的动态规划书籍,例如《算法竞赛进阶指南》、《算法与数据结构基础》等,来深入理解这种算法思想。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

贫道绝缘子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值