LeetCode
来源:互联网 发布:苹果数据线线序 编辑:程序博客网 时间:2024/06/06 12:39
Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, +
, -
, *
, /
operators and empty spaces . The integer division should truncate toward zero.
You may assume that the given expression is always valid.
Some examples:
"3+2*2" = 7" 3/2 " = 1" 3+5 / 2 " = 5
Note: Do not use the eval
built-in library function.
计算一个字符串的值。
利用一个栈,将数字计算出来丢进去(+-注意改变正负),并在遍历时计算乘除法。最后只要将栈中数字都加起来即可。时间复杂度O(n),空间复杂度O(n)
class Solution {public: int calculate(string s) { stack<int> st; int sum = 0; char sign = '+'; for (int i = 0; i < s.length(); ++i) { if (s[i] == ' ') continue; if (s[i] >= '0' && s[i] <= '9') { sum = sum * 10 + (s[i] - '0'); continue; } if (sign == '+') { st.push(sum); sum = 0; } else if (sign == '-') { st.push(-sum); sum = 0; } else if (sign == '*') { int num = st.top(); st.pop(); st.push(num * sum); sum = 0; } else if (sign == '/') { int num = st.top(); st.pop(); st.push(num / sum); sum = 0; } sign = s[i]; } if (sign == '+') { st.push(sum); sum = 0; } else if (sign == '-') { st.push(-sum); sum = 0; } else if (sign == '*') { int num = st.top(); st.pop(); st.push(num * sum); sum = 0; } else if (sign == '/') { int num = st.top(); st.pop(); st.push(num / sum); sum = 0; } int ans = 0; while (!st.empty()) { ans += st.top(); st.pop(); } return ans; }};
阅读全文
0 0
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- Hypervisor介绍
- Goroutine与Thread差异
- UVA11478 Halum 解题报告【图论】【二分答案】【SPFA】【差分约束系统】
- SVM学习笔记-软间隔SVM
- MongoDB与Redis的比较
- LeetCode
- Java8源码-详解fail-fast
- 基于数组的栈实现
- SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)
- cookie之增删改查
- Spring MVC的使用
- ajax请求异步
- 函数指针
- javascript学习(十五)— 创建对象