[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 ...
随机推荐
- leetcode笔记:Bulls and Cows
一. 题目描写叙述 You are playing the following Bulls and Cows game with your friend: You write down a numbe ...
- js 正则表达式校验必须包含字母、数字、特殊字符
1.情景展示 在注册时,密码要求必须同时包含:字母.数字.特殊字符,如何实现? 2.原因分析 用正则表达式进行校验,是最方便的! 3.解决方案 // 密码必须由 8-64位字母.数字.特殊符号组成 ...
- 使用Bootstrap+metisMenu完成简单的后台管理界面
零. 写在前面 作者最近在一个小项目中需要写后台管理界面,在互联网上绕了一圈,最后决定使用Bootstrap+metisMenu来完成.理由1:Bootstrap是目前流行的前端框架,风格简约,简单易 ...
- python模块之HTMLParser抓页面上的所有URL链接
# -*- coding: utf-8 -*- #python 27 #xiaodeng #python模块之HTMLParser抓页面上的所有URL链接 import urllib #MyParse ...
- 用FireBreath来编写跨浏览器插件
这是对于公司某个需求的临时研究,最后经过简单实验放弃了这个方案,因为编写插件不能满足需求. 下面着重讲一下FireBreath编译. 首先根据文档,用git clone下载Firebreath源码(不 ...
- Hopfield神经网络和TSP问题
一.TSP问题 旅行商问题,又叫货郎担问题.它是指如下问题:在完全图中寻找一条最短的哈密尔顿回路. 哈密尔顿回路问题:给定一个图,判断图中是否存在哈密尔顿回路. 哈密尔顿回路:寻找一条回路,经过图中所 ...
- javascript 基础知识学习1
JavaScript 是脚本语言.浏览器会在读取代码时,逐行地执行脚本代码.而对于传统编程来说,会在执行前对所有代码进行编译.基础知识:1).JavaScript 对大小写敏感.JavaScript ...
- iOS开发调试Reveal使用
推荐通过Xcode中加断点的方式集成Reveal(小缺陷,当你禁用断点时或者不用Xcode而用Appcode开发时,这个方式是不管用). 打开您的iOS工程,选择 View → Navigators ...
- memcached完全剖析--1. memcached的基础
翻译一篇技术评论社的文章,是讲memcached的连载.fcicq同学说这个东西很有用,希望大家喜欢. 发表日:2008/7/2 作者:长野雅广(Masahiro Nagano) 原文链接:http: ...
- 如何使两台机器不通过密码连接起来(linux)
要求服务器10.96.22.40不通过密码直接连接服务器10.96.21.53 1:准备必须的软件 A:服务器40和53同时安装所需软件 yum -y install openssh-server o ...