本博客介绍leetcode上的一道不难,但是比较经典的算法题。

题目如下:

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:

也可以直接参考 https://leetcode.com/problems/basic-calculator/

这是简单的加减计算运算题,一个直观的思路是运用栈,以及用后缀表达式求值。实现这一种算法,需要构造两个栈,分别是运算符栈和数字栈,然后将输入的中序表达式在转化为后续表达式的过程中求值。

考虑到这道题目的特殊性,运算符只有加减和括号,我们可以转化加减运算符为(±1),这样可以省略计算时的判断语句,而直接将转化后的运算符数作为被加(减)数的系数

这是我的代码

int calculate(string s) {
s.push_back('#'); //防止栈溢出
stack<int>num; //数字栈
stack<int>oper; //运算符栈
for(int i=; i<s.length()-;++i)
{
if(isdigit(s[i])) //判断数字,压入数字栈
{
int temp = s[i]-'';
while(++i && isdigit(s[i]))
{
temp = temp * + s[i] - '';
}
num.push(temp);
}
switch (s[i]){
case '(': //'('直接压入栈,其代表数为0
oper.push();
break;
case '+':
case '-':
if(!oper.empty() && oper.top() != ) //栈中有加减运算符,则先弹出,再压入现在的运算符
{
int num1 = num.top(); num.pop();
int num2 = num.top(); num.pop();
num.push(num2 + num1 * oper.top());
oper.pop();
}
if(s[i] == '-')
oper.push(-);
else oper.push();
break;
case ')': //为')',则一直弹出栈至弹出第一个'('
if(oper.top() == )
oper.pop();
else
{
int num1 = num.top(); num.pop();
int num2 = num.top(); num.pop();
num.push(num2 + num1 * oper.top());
oper.pop();
oper.pop();
}
break;
case '#':
break;
}
}
if(oper.empty())
return num.top();
else
{
int num1 = num.top(); num.pop();
int num2 = num.top(); num.pop();
return (num2 + num1 * oper.top());
}
}

其实这个算法的效率并不是很高,原因在于,每个数字都要压栈、退栈,每个操作符(除了')')也同样如此。

下面这个算法是讨论区上面的比较优秀的算法,其亮点是

  1. 用独立的变量存储上次的数字和加减运算符,在n次连续加减运算时省略了分别n-1次出入栈;
  2. 遇到'(',只压入前面的加减运算符,默认为加法。
class Solution {
public:
int calculate(string s) {
stack <int> nums, ops;
int num = ;
int rst = ;
int sign = ;
for (char c : s) {
if (isdigit(c)) {
num = num * + c - '';
}
else {
rst += sign * num;
num = ;
if (c == '+') sign = ;
if (c == '-') sign = -;
if (c == '(') {
nums.push(rst);
ops.push(sign);
rst = ;
sign = ;
}
if (c == ')' && ops.size()) {
rst = ops.top() * rst + nums.top();
ops.pop(); nums.pop();
}
}
}
rst += sign * num;
return rst;
}
};

也可以参考https://leetcode.com/discuss/53921/16-ms-solution-in-c-with-stacks

Basic Calculator的更多相关文章

  1. [LeetCode] Basic Calculator II 基本计算器之二

    Implement a basic calculator to evaluate a simple expression string. The expression string contains ...

  2. [LeetCode] Basic Calculator 基本计算器

    Implement a basic calculator to evaluate a simple expression string. The expression string may conta ...

  3. Basic Calculator II

    Implement a basic calculator to evaluate a simple expression string. The expression string contains ...

  4. 数据结构与算法(1)支线任务2——Basic Calculator

    题目:https://leetcode.com/problems/basic-calculator/ Implement a basic calculator to evaluate a simple ...

  5. LeetCode#227.Basic Calculator II

    题目 Implement a basic calculator to evaluate a simple expression string. The expression string contai ...

  6. Java for LeetCode 227 Basic Calculator II

    Implement a basic calculator to evaluate a simple expression string. The expression string contains ...

  7. Java for LeetCode 224 Basic Calculator

    Implement a basic calculator to evaluate a simple expression string. The expression string may conta ...

  8. LeetCode Basic Calculator II

    原题链接在这里:https://leetcode.com/problems/basic-calculator-ii/ Implement a basic calculator to evaluate ...

  9. LeetCode Basic Calculator

    原题链接在这里:https://leetcode.com/problems/basic-calculator/ Implement a basic calculator to evaluate a s ...

随机推荐

  1. JsonException: Max allowed object depth reached while trying to export from type System.Single

    在进行类转json字符串时,报错JsonException: Max allowed object depth reached while trying to export from type Sys ...

  2. JavaScript的toString()和valueof()方法

    toString()方法: 函数:函数 (function(){}).toString(); //返回"function(){}" typeof((function(){}).to ...

  3. 成功部署SSIS中含有Oracle数据库连接的ETL包

    RT,正式写之前,我想说,真TMD不容易!!! 写博客,责任心,很重要 在百度搜出来的内地博客技术文章(CSDN.ITEYE.CNBLOGS……),大部分都是不全面,只针对一个遇到的问题点的记录,可以 ...

  4. XXX esx.problem.syslog.nonpersistent.formatOnHost not found XXX

    ESXi 主机的摘要选项卡报告以下错误:配置问题:XXX esx.problem.syslog.nonpersistent.formatOnHost 未找到 XXX (2101811)   Sympt ...

  5. 剑指Offer:面试题32——从1到n整数中1出现的次数(java实现)

    问题描述: 输入一个整数n,求1到n这n个整数的十进制表示中1出现的次数.例如输入12,从1到12这些整数中包含1的数字有1,10,11,12,1一共出现了5次. 思路:(不考虑时间效率的解法,肯定不 ...

  6. CentOS7中升级Docker版本

    参考:http://blog.csdn.net/liumiaocn/article/details/52130852

  7. 关于html自闭合标签要不要加空格和斜杠的问题?

    问题描述:可能很多人都遇到过这个问题,写网页时,link img br input等等这些标签时到底要不要在结尾加上空格和斜杠呢? 我曾经貌似在<编写高质量代码>上看到过这样的介绍,遇到l ...

  8. Window 对象详解 转自 http://blog.csdn.net/jcx5083761/article/details/41243697

    详解HTML中的window对象和document对象 标签: HTMLwindowdocument 2014-11-18 11:03 5884人阅读 评论(0) 收藏 举报 分类: HTML& ...

  9. 获取iPhone 联系人列表,并且根据分析得到的姓名首字母进行排序

    获取手机联系人以iOS9为分界点,大家都知道到了iOS9很多方法都更新了,好多接口都弃用,被新的接口代替.这Demo种有新旧两个接口,使用前判断当前iOS版本. 下面是Demo连接地址:Github的 ...

  10. BitLocker 加密工具挂起和恢复命令行(windows7)

    如果你的硬盘使用BitLocker加密了,但是有时候需要高效率的硬盘做某些事情,可以暂时挂起加密,命令行如下方便做个bat. 挂起: manage-bde -protectors -disable C ...