LintCode 367,368
题目:
Given an expression string array, return the final result of this expression
Example 1:
For the expression 2*6-(23+7)/(1+2)
,
Input:
["2", "", "6", "-", "(","23", "+", "7", ")", "/", "(", "1", "+", "2", ")"]
Output:
2
Example 2:
For the expression 4-(2-3)*2+5/5
,
Input:
["4", "-", "(", "2","-", "3", ")", "", "2", "+", "5", "/", "5"]
Output:
7
Notice
The expression contains only integer, +, -, *, /, (, ).
import java.util.*;
public class Solution {
public static void main(String[] args) {
String[] express = "2 * 6 - ( 23 + 7 ) / ( 1 + 2 )".split(" ");
System.out.println(expressionEvaluation(express));
String[] express2 = "3 + 6 / 2".split(" ");
System.out.println(expressionEvaluation(express2));
}
public static int expressionEvaluation(String[] express){
Map<String, Integer> map = new HashMap<>();
map.put("+", 1);
map.put("-", 1);
map.put("*", 2);
map.put("/", 2);
int priority = 0;
Deque<Operation> op_stack = new LinkedList<>();
Deque<Integer> num_stack = new LinkedList<>();
String str;
for (int i=0; i<=express.length; i++){
if (i<express.length){
str = express[i];
}else{
str = "-";
}
if (map.keySet().contains(str)){
Operation operation = new Operation(str, priority+map.get(str));
while (!op_stack.isEmpty() && operation.priority<=op_stack.peekLast().priority){
String curOperation = op_stack.pollLast().op;
Integer curRes = null;
int b = num_stack.pollLast();
int a = num_stack.pollLast();
if (curOperation.equals("+")){
curRes = a+b;
}else if (curOperation.equals("-")){
curRes = a-b;
}else if (curOperation.equals("*")){
curRes = a*b;
}else if (curOperation.equals("/")){
curRes = a/b;
}
num_stack.offerLast(curRes);
}
op_stack.offerLast(operation);
}else if (str.equals("(")){
priority += 10;
}else if (str.equals(")")){
priority -= 10;
}else {
int num = Integer.parseInt(str);
num_stack.offerLast(num);
}
}
return num_stack.peekLast();
}
static class Operation{
String op;
int priority;
Operation(String op, int priority){
this.op = op;
this.priority = priority;
}
}
}
网友评论