[Leetcode]Basic Calculator
来源:互联网 发布:mac隐藏的照片 编辑:程序博客网 时间:2024/06/06 12:45
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
Note: Do not use the eval
built-in library function.
class Solution {public: /*algorithm: stack soluton two stack: operand stack, and operator stack transform it to reverse polish notation,then compute but we can skip this step one pass */ void tryExecute(stack<int>&opStk,stack<int>&numStk){ if(numStk.size() < 2 || opStk.empty())return; int op = opStk.top(); if(op =='+' || op == '-'){ int r = numStk.top();numStk.pop(); int l = numStk.top();numStk.pop(); numStk.push(op == '+'?(l+r):(l-r)); opStk.pop(); } } int numLength(string &s,int start){ int i = start; for(;i < s.size() && isdigit(s[i]);i++); return i - start; } int calculate(string s) { stack<int>opStk,numStk; int next; for(int i = 0;i < s.size();){ char c = s[i]; next = i + 1; if(c == '(')opStk.push(c); else if(c == ')'){ opStk.pop(); tryExecute(opStk,numStk); } else if(c == '+' || c == '-') opStk.push(c); else if(isdigit(c)){ int len = numLength(s,i); numStk.push(stoi(s.substr(i,len))); tryExecute(opStk,numStk); next = i + len; } //update i pos i = next; } return numStk.top(); }};
0 0
- 【LeetCode】Basic Calculator && Basic Calculator II
- LeetCode - Basic Calculator & Basic Calculator II
- Leetcode之Basic Calculator & Basic Calculator II
- [leetcode] Basic Calculator
- Basic Calculator - LeetCode 224
- LeetCode Basic Calculator
- leetcode:Basic Calculator
- [leetcode][math] Basic Calculator
- [LeetCode] Basic Calculator
- Leetcode 224: Basic Calculator
- leetcode 224 Basic Calculator
- [LeetCode] Basic Calculator II
- [leetcode] Basic Calculator II
- [Leetcode] Basic Calculator
- leetcode Basic Calculator
- leetcode Basic Calculator II
- LeetCode-Basic Calculator
- leetcode Basic Calculator 栈
- iOS程序员面试要注意的几个问题
- 精通脚本黑客
- 个人常用iOS第三方库以及XCode插件介绍
- c++ 模板函数,类模板,仿函数使用实例代码
- python笔记1
- [Leetcode]Basic Calculator
- UIAlerViewController的使用
- 【springmvc】java web使用ajaxSubmit方法实现Excel文件上传
- C++ 函数返回引用
- Scala学习笔记--数组
- 今日总结
- iOS高效编程秘诀—坚持好的编程习惯
- 《剑指offer》之从上往下打印二叉树
- 编写高质量的代码应从命名开始