当前位置:网站首页>LeetCode_栈_困难_227.基本计算器(不含乘除)
LeetCode_栈_困难_227.基本计算器(不含乘除)
2022-07-01 02:45:00 【一瓢江湖我沉浮】
1.题目
给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。
注意:不允许使用任何将字符串作为数学表达式计算的内置函数,比如 eval() 。
示例 1:
输入:s = “1 + 1”
输出:2
示例 2:
输入:s = " 2-1 + 2 "
输出:3
示例 3:
输入:s = “(1+(4+5+2)-3)+(6+8)”
输出:23
提示:
1 <= s.length <= 3 * 105
s 由数字、‘+’、‘-’、‘(’、‘)’、和 ’ ’ 组成
s 表示一个有效的表达式
‘+’ 不能用作一元运算(例如,“+1” 和 “+(2 + 3)” 无效)
‘-’ 可以用作一元运算(即 “-1” 和 “-(2 + 3)” 是有效的)
输入中不存在两个连续的操作符
每个数字和运行的计算将适合于一个有符号的 32 位整数
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/basic-calculator
2.思路
(1)栈
思路参考本题官方题解。
3.代码实现(Java)
//思路1————栈
class Solution {
public static int calculate(String s) {
int res = 0;
int length = s.length();
//sign 记录每个数之前的符号,对于表达式中的第一个数,默认其符号为 '+',即用 1 表示
int sign = 1;
Stack<Integer> opsStack = new Stack<>();
opsStack.push(1);
for (int i = 0; i < length; ) {
switch (s.charAt(i)) {
case ' ':
//遇到空格时直接跳过
i++;
break;
case '+':
sign = opsStack.peek();
i++;
break;
case '-':
sign = -opsStack.peek();
i++;
break;
case '(':
opsStack.push(sign);
i++;
break;
case ')':
opsStack.pop();
i++;
break;
default:
//表示遍历表达式时遇到的每一个数
int num = 0;
while (i < length && Character.isDigit(s.charAt(i))) {
num = num * 10 + (s.charAt(i) - '0');
i++;
}
res += sign * num;
break;
}
}
return res;
}
}
边栏推荐
- [wechat applet development] style summary
- How do I hide div on Google maps- How to float a div over Google Maps?
- 基于Pytorch完整的训练一个神经网络并进行验证
- CentOS installs multiple versions of PHP and switches
- SAP ALV summary is inconsistent with exported excel summary data
- [JS] [Nuggets] get people who are not followers
- Record a service deployment failure troubleshooting
- js中的原型和原型链
- Desai wisdom number - other charts (parallel coordinate chart): employment of fresh majors in 2021
- Mouse over effect IV
猜你喜欢

基于OPENCV和图像减法的PCB缺陷检测

旷世轻量化网络ShuffulNetV2学习笔记

Restcloud ETL practice data row column conversion

Xception learning notes

园区运营效率提升,小程序容器技术加速应用平台化管理

Detailed data governance knowledge system

Youmeng (a good helper for real-time monitoring of software exceptions: crash) access tutorial (the easiest tutorial for Xiaobai with some foundation)

php批量excel转word

Dell server restart Idrac method

Image preloading in JS
随机推荐
Pycharm 打开远程目录 Remote Host
7_ Openresty installation
Borrowing constructor inheritance and composite inheritance
Go import self built package
[PR # 5 A] two way running (state pressure DP)
Dell服务器重启iDRAC方法
Mouse over effect 9
Thread Detach
Pulsar Geo Replication/灾备/地域复制
Cluster method synchronous execution framework suona
Mouse over effect I
RestCloud ETL WebService数据同步到本地
【PR #5 A】双向奔赴(状压DP)
记一次服务部署失败问题排查
The latest wechat iPad protocol code obtains official account authorization, etc
522. Longest special sequence II
园区运营效率提升,小程序容器技术加速应用平台化管理
小程序自定义顶部导航栏,uni-app微信小程序自定义顶部导航栏
Mnasnet learning notes
Map array function