数值表达式的计算-leetcode basic calculator

 1 public class Solution {
 2     
 3     int priority(char op){
 4         if(op == '+' || op == '-') return 1;
 5         else return 2;
 6     }
 7     boolean isNum(String s){
 8         return Character.isDigit(s.charAt(0));
 9     }
10     boolean isOp(char ch){
11         return ch == '+' || ch == '-' || ch == '*' || ch == '/';
12     }
13     long cal(long num1, char op, long num2){
14         if(op == '-') return num1 - num2;
15         else if(op == '+') return num1 + num2;
16         else if(op == '*') return num1 * num2;
17         else return num1 / num2;
18     }
19     void popOpAndTwoNums(Stack opStack, Stack numStack){
20         char op = opStack.pop();
21         long num2 = numStack.pop(), num1 = numStack.pop();
22         long num = cal(num1, op, num2);
23         numStack.push(num);
24     }
25     public ArrayList split(String s){
26         ArrayList array = new ArrayList();
27         int i = 0;
28         while(i < s.length()){
29             if(s.charAt(i) == '(' || s.charAt(i) == ')' || isOp(s.charAt(i))){
30                 array.add(s.substring(i, i + 1));
31                 i++;
32             }else if(s.charAt(i) == ' '){
33                 i++;
34                 continue ;
35             }else{
36                 int j = i;
37                 while(j < s.length() && Character.isDigit(s.charAt(j))) j++;
38                 array.add(s.substring(i, j));
39                 i = j;
40             }
41         }
42         return array;
43     }
44     public int calculate(String s) {
45         ArrayList array = split(s);
46         Stack opStack = new Stack();
47         Stack numStack = new Stack();
48         for(int i = 0; i < array.size(); i++){
49             if(isNum(array.get(i))){
50                 numStack.push(Long.parseLong(array.get(i)));
51             }else{
52                 char ch = array.get(i).charAt(0);
53                 if(ch == '('){
54                     opStack.push(ch);
55                 }else if(ch == ')'){
56                     while(opStack.peek() != '('){
57                         popOpAndTwoNums(opStack, numStack);
58                     }
59                     opStack.pop();
60                 }else{
61                     if(opStack.size() > 0 && isOp(opStack.peek()) && priority(ch) <= priority(opStack.peek())){
62                         popOpAndTwoNums(opStack, numStack);
63                     }
64                     opStack.push(ch);
65                 }
66             }
67         }
68         while(numStack.size() > 1){
69             popOpAndTwoNums(opStack, numStack);
70         }
71         return numStack.peek().intValue();
72     }
73 }

 

转载于:https://www.cnblogs.com/liqiniuniu/p/11024229.html

你可能感兴趣的:(数值表达式的计算-leetcode basic calculator)