欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

leetcode 224. Basic Calculator | 224. 基本计算器(中缀表达式求值)

发布时间:2024/2/28 编程问答 43 豆豆
生活随笔 收集整理的这篇文章主要介绍了 leetcode 224. Basic Calculator | 224. 基本计算器(中缀表达式求值) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

题目

https://leetcode.com/problems/basic-calculator/

题解

中缀表达式求值,之前学数据结构的笔记:

class Solution {public int calculate(String s) {if (s.trim().startsWith("-")) s = "0" + s;Stack<Integer> numStack = new Stack<>();Stack<Character> opStack = new Stack<>();int cur = 0;boolean pending = false;for (char c : s.toCharArray()) {if (c == ' ') {// pass} else if (c == '(') {if (pending) {numStack.push(cur);cur = 0;pending = false;}opStack.push(c);} else if (c == ')') {if (pending) {numStack.push(cur);cur = 0;pending = false;}char op = opStack.pop();while (op != '(') {int b = numStack.pop();int a = numStack.pop();numStack.push(cal(a, b, op));op = opStack.pop();}} else if (c >= '0' && c <= '9') {cur *= 10;cur += c - '0';pending = true;} else {if (pending) {numStack.push(cur);cur = 0;pending = false;}if (!opStack.isEmpty() && opStack.peek() != '(') {char op = opStack.pop();int b = numStack.pop();int a = numStack.pop();numStack.push(cal(a, b, op));}opStack.push(c);}}if (pending) {numStack.push(cur);}if (!opStack.isEmpty()) {char op = opStack.pop();int b = numStack.pop();int a = numStack.pop();numStack.push(cal(a, b, op));}return numStack.pop();}public int cal(int a, int b, char op) {return op == '+' ? a + b : a - b;} }

总结

以上是生活随笔为你收集整理的leetcode 224. Basic Calculator | 224. 基本计算器(中缀表达式求值)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。