leet-code/src/main/java/leetcode/editor/cn/BasicCalculator.java
2021-06-03 16:54:46 +08:00

89 lines
2.0 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。
//
//
//
// 示例 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 表示一个有效的表达式
//
// Related Topics 栈 数学
// 👍 571 👎 0
package leetcode.editor.cn;
import java.util.*;
//224:基本计算器
public class BasicCalculator {
public static void main(String[] args) {
//测试代码
Solution solution = new BasicCalculator().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int calculate(String s) {
Deque<Integer> ops = new LinkedList<Integer>();
ops.push(1);
int sign = 1;
int ret = 0;
int n = s.length();
int i = 0;
while (i < n) {
if (s.charAt(i) == ' ') {
i++;
} else if (s.charAt(i) == '+') {
sign = ops.peek();
i++;
} else if (s.charAt(i) == '-') {
sign = -ops.peek();
i++;
} else if (s.charAt(i) == '(') {
ops.push(sign);
i++;
} else if (s.charAt(i) == ')') {
ops.pop();
i++;
} else {
long num = 0;
while (i < n && Character.isDigit(s.charAt(i))) {
num = num * 10 + s.charAt(i) - '0';
i++;
}
ret += sign * num;
}
}
return ret;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}