当前位置:网站首页>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;
}
}
边栏推荐
- 视觉特效,图片转成漫画功能
- Mouse over effect II
- Complete training and verification of a neural network based on pytorch
- Pulsar geo replication/ disaster recovery / regional replication
- Mouse over effect IV
- Mouse over effect 9
- 7_ Openresty installation
- 集群方法同步执行框架 Suona
- MCU firmware packaging Script Software
- Nacos configuration center tutorial
猜你喜欢

js中的原型和原型链

pycharm 软件deployment 灰色 无法点

UE4渲染管线学习笔记

PCB defect detection based on OpenCV and image subtraction

RestCloud ETL WebService数据同步到本地

联想X86服务器重启管理控制器(XClarity Controller)或TSM的方法

Xception学习笔记

Pychar open remote directory remote host

在unity中使用jieba分词的方法

The latest wechat iPad protocol code obtains official account authorization, etc
随机推荐
Restcloud ETl数据通过时间戳实现增量数据同步
Record a service deployment failure troubleshooting
Mouse over effect V
Mnasnet learning notes
Viewing JVM parameters
查看 jvm 参数
Mouse over effect VI
centos 安装多个版本的php并切换
servlet【初识】
DenseNet网络论文学习笔记
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)
robots.txt限制搜索引擎收录
[graduation season · advanced technology Er] - summary from graduation to work
import tensorflow. contrib. Slim as slim error
Zero foundation self-study SQL course | window function
5款主流智能音箱入门款测评:苹果小米华为天猫小度,谁的表现更胜一筹?
Here comes the share creators budding talent training program!
JS anti shake and throttling
If I am in Beijing, where is a better place to open an account? In addition, is it safe to open a mobile account?