​LeetCode刷题实战227:基本计算器 II

简介: 算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 基本计算器 II,我们先来看题面:https://leetcode-cn.com/problems/basic-calculator-ii/

Given a string s which represents an expression, evaluate this expression and return its value.

The integer division should truncate toward zero.

给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。整数除法仅保留整数部分。

示例

示例 1:
输入:s = "3+2*2"
输出:7
示例 2:
输入:s = " 3/2 "
输出:1
示例 3:
输入:s = " 3+5 / 2 "
输出:5

解题


思路:利用栈的方式解决运算优先级的问题 当为加减时放入栈中 当为乘除时讲栈顶元素与最近获得一个数进行运算

因为所有输入都是合法的  所有我们预存上一个运算符和数字 这样简便操作

class Solution {
    public int calculate(String s) {
       int result=0,len=s.length(),num=0;
        char op='+'; //初始上一个运算符为加法 上个数字为0
        Stack<Integer> stack=new Stack<Integer>();
        for(int i=0;i<len;i++){
            char c=s.charAt(i);
            if(c>='0'){
                num=num*10+s.charAt(i)-'0';
            }
            if(c<'0'&&c!=' '||i==len-1){
                if(op=='+') stack.push(num);
                if(op=='-') stack.push(-num);
                if(op=='*'||op=='/'){
                    int temp=(op=='*')?stack.pop()*num:stack.pop()/num;
                    stack.push(temp);
                }
                 op=s.charAt(i);
                 num=0;
            }
        }
        while(!stack.isEmpty()){
            result+=stack.pop();
        }
        return result;
    }
}

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

相关文章
|
2月前
|
机器学习/深度学习 算法
力扣刷题日常(一)
力扣刷题日常(一)
20 2
|
2月前
|
存储 索引
《LeetCode》—— LeetCode刷题日记
《LeetCode》—— LeetCode刷题日记
|
2月前
|
搜索推荐
《LeetCode》——LeetCode刷题日记3
《LeetCode》——LeetCode刷题日记3
|
2月前
|
容器
《LeetCode》——LeetCode刷题日记1
《LeetCode》——LeetCode刷题日记1
|
2月前
|
算法
LeetCode刷题---21.合并两个有序链表(双指针)
LeetCode刷题---21.合并两个有序链表(双指针)
|
2月前
|
算法
LeetCode刷题---19. 删除链表的倒数第 N 个结点(双指针-快慢指针)
LeetCode刷题---19. 删除链表的倒数第 N 个结点(双指针-快慢指针)
|
2月前
|
算法 测试技术
LeetCode刷题--- 430. 扁平化多级双向链表(深度优先搜索)
LeetCode刷题--- 430. 扁平化多级双向链表(深度优先搜索)
|
2月前
|
存储
实现单链表的基本操作(力扣、牛客刷题的基础&笔试题常客)
实现单链表的基本操作(力扣、牛客刷题的基础&笔试题常客)
144 38
|
8天前
刷题之Leetcode160题(超级详细)
刷题之Leetcode160题(超级详细)
11 0
|
8天前
刷题之Leetcode206题(超级详细)
刷题之Leetcode206题(超级详细)
21 0
刷题之Leetcode206题(超级详细)

热门文章

最新文章