LeetCode Basic Calculator

本文详细解析了LeetCode上的基本计算器题目,通过具体实例讲解了如何实现一个简单的表达式求值器,包括数字处理、符号识别及括号的使用等核心步骤,并提供了完整的Java代码示例。

原题链接在这里:https://leetcode.com/problems/basic-calculator/

题目:

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 .

You may assume that the given expression is always valid.

Some examples:

"1 + 1" = 2
" 2-1 + 2 " = 3
"(1+(4+5+2)-3)+(6+8)" = 23 

题解:

思路:1. 遇到数字位,看后一位是否为数字,若是位数字,当前位需要进十.

2. 开始设sign = 1,若遇到 ' - ', sign 改为 -1,若遇到 '+',sign改回1.

3. 遇到 '(', 压栈,先压之前的res,后压sign,然后初始化res和sign.

4. 遇到')' ,出栈,当前res先乘pop() 出来的 sign,再加上pop()出来的之前结果.

Note:1.遇到数字时需要生成一个新的cur 用来存储当前数,随后再用cur求res,不能直接求res,'-' 时会出问题。

Time Complexity: O(s.length()). Space: O(s.length()), stack 的大小.

AC Java: 

 1 public class Solution {
 2     public int calculate(String s) {
 3         if(s == null || s.length() == 0){
 4             return -1;
 5         }
 6         int res = 0;
 7         int sign = 1;
 8         Stack<Integer> stk = new Stack<Integer>();
 9         for(int i = 0; i<s.length(); i++){
10             char c = s.charAt(i);
11             if(Character.isDigit(c)){
12                 int cur = (int)(c-'0');
13                 while(i+1 < s.length() && Character.isDigit(s.charAt(i+1))){
14                     cur = cur*10 + (int)(s.charAt(i+1) - '0');
15                     i = i+1;
16                 }
17                 res += sign*cur;
18             }else if(c == '-'){
19                 sign = -1;
20             }else if(c == '+'){
21                 sign = 1;
22             }else if(c == '('){
23                 stk.push(res);
24                 res = 0;
25                 stk.push(sign);
26                 sign = 1;
27             }else if(c == ')'){
28                 res = res*stk.pop() + stk.pop();
29             }
30         }
31         return res;
32     }
33 }

跟上Basic Calculator II

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/4825019.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值