Basic Calculator

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.

Basic Calculator II

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, +, -, *, and / operators. 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

一个很详细的解释:http://www.geeksforgeeks.org/expression-evaluation/ 比这道题还难点

思路就是两个stack,一个存数字一个存符号。如果遇到数字直接存到数字stack;如果遇到符号,有几种情况:

1.当前符号比上一个符号优先级高,比如* 高于+,那么直接进栈

2.当前符号低于上一个,那么就要把所有已经在stack里面优先于当前符号的全算完,再推进当前符号

3.当前符号是“(”,直接push

4.当前符号是“)”,就要把所有“(”以前的符号全部算完

这道题只有“+”号与“-”号,不用判断符号的优先级。

class Solution {
private:
bool isOK(char op1, char op2) {
if (op1 == '*' || op1 == '/' || op2 == ')') return true;
else return op2 == '+' || op2 == '-';
}
int calc(int a, int b, char op) {
if (op == '+') return a + b;
else if (op == '-') return a - b;
else if (op == '*') return a * b;
else return a / b;
}
public:
int calculate(string s) {
stack<int> stk_val;
stack<char> stk_op;
int res = , tmp;
for (int i = ; i <= s.length(); ++i) {
//操作数
if (i < s.length() && isdigit(s[i])) {
res = ;
while (i < s.length() && isdigit(s[i])) {
res *= ;
res += s[i++] - '';
}
stk_val.push(res);
}
//运算符
if (i == s.length() || s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/' || s[i] == ')') {
while (!stk_op.empty() && stk_op.top() != '(' && (i == s.length() || isOK(stk_op.top(), s[i]))) {
tmp = stk_val.top();
stk_val.pop();
stk_val.top() = calc(stk_val.top(), tmp, stk_op.top());
stk_op.pop();
}
if (i == s.length()) break;
else if (s[i] == ')') stk_op.pop();
else stk_op.push(s[i]);
} else if (s[i] == '(') {
stk_op.push(s[i]);
}
}
return stk_val.top();
}
};

LintCode上有一道相同的题,但是运算符不仅包含"+"、"-",还包含了 "*" 和 "/",不过不用自己解析操作数了。

Expression Evaluation

Given an expression string array, return the final result of this expression

For the expression 2*6-(23+7)/(1+2), input is

[
"2", "*", "6", "-", "(",
"23", "+", "7", ")", "/",
(", "1", "+", "2", ")"
],

return 2

Note

The expression contains only integer+-*/().

 class Solution {
public:
/**
* @param expression: a vector of strings;
* @return: an integer
*/
int calulate(int a, int b, const string &op) {
if (op == "+") return a + b;
else if (op == "-") return a - b;
else if (op == "*") return a * b;
else return a / b;
}
bool isOK(const string &op1, const string &op2) {
if (op1 == "*" || op1 == "/" || op2 == ")") return true;
else return op2 == "+" || op2 == "-";
}
int evaluateExpression(vector<string> &expression) {
// write your code here
if (expression.empty()) return ;
stack<int> stk_val;
stack<string> stk_op;
for (int i = ; i <= expression.size(); ++i) {
if (i < expression.size() && isdigit(expression[i][])) {
stk_val.push(atoi(expression[i].c_str()));
} else if (i == expression.size() || expression[i] != "(") {
while (!stk_op.empty() && stk_op.top() != "("
&& (i == expression.size() || isOK(stk_op.top(), expression[i]))) {
int tmp = stk_val.top();
stk_val.pop();
stk_val.top() = calulate(stk_val.top(), tmp, stk_op.top());
stk_op.pop();
}
if (i == expression.size()) break;
else if (expression[i] == ")") stk_op.pop();
else stk_op.push(expression[i]);
} else {
stk_op.push(expression[i]);
}
}
return stk_val.top();
}
};

下面是求表达式树,同样的算法。

Expression Tree Build

The structure of Expression Tree is a binary tree to evaluate certain expressions. All leaves of the Expression Tree have an number string value. All non-leaves of the Expression Tree have an operator string value.

Now, given an expression array, build the expression tree of this expression, return the root of this expression tree.

 

For the expression (2*6-(23+7)/(1+2)) (which can be represented by ["2" "*" "6" "-" "(" "23" "+" "7" ")" "/" "(" "1" "+" "2" ")"]). The expression tree will be like

                 [ - ]
/ \
[ * ] [ / ]
/ \ / \
[ 2 ] [ 6 ] [ + ] [ + ]
/ \ / \
[ 23 ][ 7 ] [ 1 ] [ 2 ] .

After building the tree, you just need to return root node [-].

 /**
* Definition of ExpressionTreeNode:
* class ExpressionTreeNode {
* public:
* string symbol;
* ExpressionTreeNode *left, *right;
* ExpressionTreeNode(string symbol) {
* this->symbol = symbol;
* this->left = this->right = NULL;
* }
* }
*/ class Solution {
public:
/**
* @param expression: A string array
* @return: The root of expression tree
*/
bool isOK(const string &op1, const string &op2) {
if (op1 == "*" || op1 == "/" || op2 == ")") return true;
else return op2 == "+" || op2 == "-";
}
ExpressionTreeNode* build(vector<string> &expression) {
// write your code here
stack<ExpressionTreeNode*> stk_node;
ExpressionTreeNode *left, *right, *tmp;
stack<string> stk_op;
stk_node.push(NULL);
int n = expression.size();
for (int i = ; i <= n; ++i) {
if (i < n && isdigit(expression[i][])) {
tmp = new ExpressionTreeNode(expression[i]);
stk_node.push(tmp);
} else if (i == n || expression[i] != "(") {
while (!stk_op.empty() && stk_op.top() != "(" && (i == n || isOK(stk_op.top(), expression[i]))) {
tmp = new ExpressionTreeNode(stk_op.top());
stk_op.pop();
right = stk_node.top(); stk_node.pop();
left = stk_node.top(); stk_node.pop();
tmp->left = left;
tmp->right = right;
stk_node.push(tmp);
}
if (i == n) break;
else if (expression[i] != ")") stk_op.push(expression[i]);
else stk_op.pop();
} else {
stk_op.push("(");
}
}
return stk_node.top();
}
};

[LeetCode] Basic Calculator & Basic Calculator II的更多相关文章

  1. 【LeetCode】227. Basic Calculator II 解题报告(Python)

    [LeetCode]227. Basic Calculator II 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: h ...

  2. 乘风破浪:LeetCode真题_040_Combination Sum II

    乘风破浪:LeetCode真题_040_Combination Sum II 一.前言 这次和上次的区别是元素不能重复使用了,这也简单,每一次去掉使用过的元素即可. 二.Combination Sum ...

  3. [LeetCode] 445. Add Two Numbers II 两个数字相加之二

    You are given two linked lists representing two non-negative numbers. The most significant digit com ...

  4. Leetcode:面试题68 - II. 二叉树的最近公共祖先

    Leetcode:面试题68 - II. 二叉树的最近公共祖先 Leetcode:面试题68 - II. 二叉树的最近公共祖先 Talk is cheap . Show me the code . / ...

  5. Leetcode:面试题55 - II. 平衡二叉树

    Leetcode:面试题55 - II. 平衡二叉树 Leetcode:面试题55 - II. 平衡二叉树 Talk is cheap . Show me the code . /** * Defin ...

  6. 【LeetCode】Pascal's Triangle II 解题报告

    [LeetCode]Pascal's Triangle II 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/pascals-tr ...

  7. 【LeetCode】731. My Calendar II 解题报告(Python)

    [LeetCode]731. My Calendar II 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题 ...

  8. 【LeetCode】137. Single Number II 解题报告(Python)

    [LeetCode]137. Single Number II 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/problems/single- ...

  9. 【LeetCode】113. Path Sum II 解题报告(Python)

    [LeetCode]113. Path Sum II 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fu ...

  10. 【LeetCode】227. Basic Calculator II

    Basic Calculator II Implement a basic calculator to evaluate a simple expression string. The express ...

随机推荐

  1. SpringMVC学习笔记三:拦截器

    一:拦截器工作原理 类比Struts2的拦截器,通过拦截器可以实现在调用controller的方法前.后进行一些操作. 二:拦截器实现 1:实现拦截器类 实现HandlerInterceptor 接口 ...

  2. nginx内置预定义变量

    nginx的配置文件中可以使用的内置变量以美元符$开始,也有人叫全局变量.其中,部分预定义的变量的值是可以改变的. $arg_PARAMETER 这个变量值为:GET请求中变量名PARAMETER参数 ...

  3. cocos2d-js 在线更新代码脚本 动态更新脚本程序 热更新 绕过平台审核 不需重新上架

    2014年8月15日补充 cocos2d-js 3.0 rc0 的AssetsManager有缺陷,有一些注意点:(可以阅读源代码发现) 1.旧manifest中有,但新manifest中没有的文件( ...

  4. 学习练习SQL的数据库employee文件

    这个地址是一个已经集成了employee的database的sql文件.所以你可以下载这个sql文件,然后执行sql语句到对应的数据库中,这样你就可以练习sql语句了. 第一个链接是用户指导如何使用的 ...

  5. php Socket表单提交学习一下

    <?php //发送请求指定的页面 $file = "1.php"; $filename = "gitignore.txt"; //文件名 $path = ...

  6. 读书笔记——spring cloud 中 HystrixCommand的四种执行方式简述

    读了<Spring Cloud 微服务实战>第151-154页, 总结如下: Hystrix存在两种Command,一种是HystrixCommand,另一种是HystrixObserva ...

  7. windows下命令行终端使用rz上传文件参数详解

    rz命令: (X) = option applies to XMODEM only (Y) = option applies to YMODEM only (Z) = option applies t ...

  8. Ubuntu16.04下的英文词典Artha

    地址: http://artha.sourceforge.net  http://artha.sourceforge.net/wiki/index.php/Download 在Ubuntu下可以直接安 ...

  9. iphone3g 蜂窝数据有效设置

    iphone3g 蜂窝数据有效设置 蜂窝数据     APN cmnet/空     用户名 空     A密码 空彩信(默认为空,需要控制的话,可以设置)     APN cmwap/空     用 ...

  10. Socket编程:之双机通信

    服务端: #include<sys/socket.h> #include<sys/types.h> #include<stdio.h> #include<un ...