[LeetCode] Basic Calculator & Basic Calculator II

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();
}
};
上一篇:Pascal's Triangle 2(leetcode java)


下一篇:LeetCode OJ Basic Calculator II