[LeetCode] Basic Calculator & Basic Calculator II
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.
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上有一道相同的题,但是运算符不仅包含"+"、"-",还包含了 "*" 和 "/",不过不用自己解析操作数了。
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
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的更多相关文章
- 【LeetCode】227. Basic Calculator II 解题报告(Python)
[LeetCode]227. Basic Calculator II 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: h ...
- 乘风破浪:LeetCode真题_040_Combination Sum II
乘风破浪:LeetCode真题_040_Combination Sum II 一.前言 这次和上次的区别是元素不能重复使用了,这也简单,每一次去掉使用过的元素即可. 二.Combination Sum ...
- [LeetCode] 445. Add Two Numbers II 两个数字相加之二
You are given two linked lists representing two non-negative numbers. The most significant digit com ...
- Leetcode:面试题68 - II. 二叉树的最近公共祖先
Leetcode:面试题68 - II. 二叉树的最近公共祖先 Leetcode:面试题68 - II. 二叉树的最近公共祖先 Talk is cheap . Show me the code . / ...
- Leetcode:面试题55 - II. 平衡二叉树
Leetcode:面试题55 - II. 平衡二叉树 Leetcode:面试题55 - II. 平衡二叉树 Talk is cheap . Show me the code . /** * Defin ...
- 【LeetCode】Pascal's Triangle II 解题报告
[LeetCode]Pascal's Triangle II 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/pascals-tr ...
- 【LeetCode】731. My Calendar II 解题报告(Python)
[LeetCode]731. My Calendar II 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题 ...
- 【LeetCode】137. Single Number II 解题报告(Python)
[LeetCode]137. Single Number II 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/problems/single- ...
- 【LeetCode】113. Path Sum II 解题报告(Python)
[LeetCode]113. Path Sum II 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fu ...
- 【LeetCode】227. Basic Calculator II
Basic Calculator II Implement a basic calculator to evaluate a simple expression string. The express ...
随机推荐
- Java 底层机制(JVM/堆/栈/方法区/GC/类加载)
转载:https://www.jianshu.com/p/ae97b692614e?from=timeline JVM体系结构 JVM是一种解释执行class文件的规范技术. JVM体系结构 我翻 ...
- C++ 的 runtime exception是没有扩展性的
https://groups.google.com/forum/#!topic/seastar-dev/RuK-OajeqHk https://www.google.com/search?ei=gTH ...
- js 正则表达式校验必须包含字母、数字、特殊字符
1.情景展示 在注册时,密码要求必须同时包含:字母.数字.特殊字符,如何实现? 2.原因分析 用正则表达式进行校验,是最方便的! 3.解决方案 // 密码必须由 8-64位字母.数字.特殊符号组成 ...
- CSDN开源夏令营 基于Compiz的switcher插件设计与实现之编译compiz源代码
在開始介绍之前先吐个嘈:上周我们暑期ACM集训開始了.平均下来基本上是一天一赛.有时还不止.又是多校联赛,又是CodeForces,又是TopCoder.又是BestCoder,又是AcDream.还 ...
- 小结java自带的跟锁相关的一些类
java.util.concurrent包下的一些跟锁相关的类列表 类 简介 locks.Lock接口 Lock 实现提供了比使用 synchronized 方法和语句可获得的更广泛的锁定操作.此 ...
- 4、线程范围内的数据共享之ThreadLocal
/** * 线程范围类的数据共享 * 核心:ThreadLocal类 * 实际场景: * Hibernate的getCurrentSession方法,就是从线程范围内获取存在的session,如果不存 ...
- Centos7新装配置, 并使用openvpn client长连接远程备份
1. 修改本机hostname // 查看本机hostname hostnamectl //永久性的修改主机名称, 修改完后新开的terminal中立刻生效. 也可以直接修改 /etc/hostnam ...
- iOS TableView多级列表
代码地址如下:http://www.demodashi.com/demo/15006.html 效果预览 ### 一.需求 TableView多级列表:分级展开或合并,逐级获取并展示其子级数据,可以设 ...
- Region使用全解
代码地址如下:http://www.demodashi.com/demo/14799.html 前言 Region,即为区域,它表示的是canvas图层上的某一块封闭的区域.很多时候,我们会利用Reg ...
- ibatis和myBatis打印sql语句的log4j配置文件
1/ibatis: log4j.rootLogger=debug, stdout, logfile log4j.logger.com.ibatis=DEBUG log4j.logger.com. ...