diff --git a/src/main/java/leetcode/editor/cn/BasicCalculator.java b/src/main/java/leetcode/editor/cn/BasicCalculator.java new file mode 100644 index 0000000..64e010d --- /dev/null +++ b/src/main/java/leetcode/editor/cn/BasicCalculator.java @@ -0,0 +1,89 @@ +//给你一个字符串表达式 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 ops = new LinkedList(); + 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) + +} \ No newline at end of file diff --git a/src/main/java/leetcode/editor/cn/BasicCalculator.md b/src/main/java/leetcode/editor/cn/BasicCalculator.md new file mode 100644 index 0000000..3be0502 --- /dev/null +++ b/src/main/java/leetcode/editor/cn/BasicCalculator.md @@ -0,0 +1,35 @@ +

给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。

+ +

 

+ +

示例 1:

+ +
+输入:s = "1 + 1"
+输出:2
+
+ +

示例 2:

+ +
+输入:s = " 2-1 + 2 "
+输出:3
+
+ +

示例 3:

+ +
+输入:s = "(1+(4+5+2)-3)+(6+8)"
+输出:23
+
+ +

 

+ +

提示:

+ + +
Related Topics
  • 数学
  • \n
  • 👍 571
  • 👎 0
  • \ No newline at end of file