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. qtp descriptive programming multiple language(多语言支持)

    so easy, 1,use the descriptive programming; 2,use the | chracter to seperate the different language ...

  2. django之创建第5个项目-条件语句

    1.index <!DOCTYPE html> <html lang="en"> <head> <meta charset="U ...

  3. 转 configure: error: Cannot find ldap.h

    检查下面是不是已经安装,如果没有安装之:检查:yum list openldapyum list openldap-devel安装 :yum install openldap yum install ...

  4. CentOS7下HTTP并发测试工具Apache Benchmark(AB)安装和使用

    安装: yum -y install httpd-tools 使用: ab -c -n http://10.255.67.60:1111/info -c 并发数,concurrency -n 发送多少 ...

  5. iOS12 Network框架 自签名证书认证

    发布时间:2018-09-21   技术:iOS12 xcode10 golang1.11   概述 iOS12 苹果发布了新的网络框架Network,可以更方便地操作底层网络通信了.使用TLS也很方 ...

  6. 微服务(Microservice)那点事

    WHAT - 什么是微服务 微服务简介 这次参加JavaOne2015最大的困难就是听Microservice相关的session,无论内容多么水,只要题目带microservice,必定报不上名,可 ...

  7. ext4文件系统的delalloc选项造成单次写延迟增加的分析

    最近我们的服务进程遇到kill -15后处于Z的状态,变为了僵尸进程,经过/proc/{thread_id}/stack查看其上线程的栈,发现是卡在了fwrite的过程中,而我们的系统中所有文件系统挂 ...

  8. 【备份】使用mysqldump 实现rename database name(mysql数据库改名称)

    需求:将jxl_credit改名为jxl_test;输入:jxl_credit输出: jxl_test; 实现方式:1).新建jxl_test,2).备份jxl_credit到本地,3).然后将备份数 ...

  9. linux c学习笔记----线程创建与终止

    进程原语 线程原语 描述 fork pthread_create 创建新的控制流 exit pthread_exit 从现有的控制流中退出 waitpid pthread_join 从控制流中得到退出 ...

  10. Socket模型(二):完成端口(IOCP)

    为什么要采用Socket模型,而不直接使用Socket? 原因源于recv()方法是堵塞式的,当多个客户端连接服务器时,其中一个socket的recv调用时,会产生堵塞,使其他链接不能继续.这样我们又 ...