• 计算表达式【学习算法】


    前言

    2023-9-24 23:02:07

    以下内容源自《【学习算法】》
    仅供学习交流使用

    版权

    禁止其他平台发布时删除以下此话
    本文首次发布于CSDN平台
    作者是CSDN@日星月云
    博客主页是https://blog.csdn.net/qq_51625007
    禁止其他平台发布时删除以上此话

    推荐

    计算表达式

    逆波兰表达式求值

    150. 逆波兰表达式求值

    class Solution {
        public int evalRPN(String[] tokens) {
            Stack<String> stack=new Stack();
            for(String s:tokens){
                if(s.equals("+")){
                    int b=Integer.parseInt(stack.pop());
                    int a=Integer.parseInt(stack.pop());
                    int c=a+b;
                    stack.push(Integer.toString(c));
                }else if(s.equals("-")){
                    int b=Integer.parseInt(stack.pop());
                    int a=Integer.parseInt(stack.pop());
                    int c=a-b;
                    stack.push(Integer.toString(c));
                }else if(s.equals("*")){
                    int b=Integer.parseInt(stack.pop());
                    int a=Integer.parseInt(stack.pop());
                    int c=a*b;
                    stack.push(Integer.toString(c));
                }else if(s.equals("/")){
                    int b=Integer.parseInt(stack.pop());
                    int a=Integer.parseInt(stack.pop());
                    int c=a/b;
                    stack.push(Integer.toString(c));
                }else{
                    stack.push(s);
                }
            }
            return Integer.parseInt(stack.pop());
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    中缀表达式求值

    面试题 16.26. 计算器

    LeetCode

    class Solution {
        public int calculate(String s) {
            Deque<Integer> stack = new ArrayDeque<Integer>();
            char preSign = '+';
            int num = 0;
            int n = s.length();
            for (int i = 0; i < n; ++i) {
                if (Character.isDigit(s.charAt(i))) {
                    num = num * 10 + s.charAt(i) - '0';
                }
                if (!Character.isDigit(s.charAt(i)) && s.charAt(i) != ' ' || i == n - 1) {
                    switch (preSign) {
                    case '+':
                        stack.push(num);
                        break;
                    case '-':
                        stack.push(-num);
                        break;
                    case '*':
                        stack.push(stack.pop() * num);
                        break;
                    default:
                        stack.push(stack.pop() / num);
                    }
                    preSign = s.charAt(i);
                    num = 0;
                }
            }
            int ans = 0;
            while (!stack.isEmpty()) {
                ans += stack.pop();
            }
            return ans;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    算法优先分析法

    import java.util.ArrayDeque;
    import java.util.Deque;
    import java.util.HashMap;
    import java.util.HashSet;
    
    public class Solution {
    
        public static void main(String[] args) {
    
            String token="3/2";
            int res=calculate(token);
            System.out.println(res);
    
        }
        static HashSet<Character> opSet =new HashSet<>();
        static {
            opSet.add('#');
            opSet.add('+');
            opSet.add('-');
            opSet.add('*');
            opSet.add('/');
            opSet.add('(');
            opSet.add(')');
        }
    
        static HashMap<Character,HashMap<Character,Character>> relation=new HashMap<>();
        static {
            HashMap<Character,Character> map=new HashMap<>();
            map.put('+','>');
            map.put('-','>');
            map.put('*','<');
            map.put('/','<');
            map.put('(','<');
            map.put(')','>');
            map.put('#','>');
            relation.put('+',map);
            relation.put('-',map);
    
            map=new HashMap<>();
            map.put('+','>');
            map.put('-','>');
            map.put('*','>');
            map.put('/','>');
            map.put('(','<');
            map.put(')','>');
            map.put('#','>');
            relation.put('*',map);
            relation.put('/',map);
    
            map=new HashMap<>();
            map.put('+','<');
            map.put('-','<');
            map.put('*','<');
            map.put('/','<');
            map.put('(','<');
            map.put(')','=');
    
            relation.put('(',map);
    
            map=new HashMap<>();
            map.put('+','>');
            map.put('-','>');
            map.put('*','>');
            map.put('/','>');
    
            map.put(')','>');
            map.put('#','>');
            relation.put(')',map);
    
    
            map=new HashMap<>();
            map.put('+','<');
            map.put('-','<');
            map.put('*','<');
            map.put('/','<');
            map.put('(','<');
    
            map.put('#','=');
            relation.put('#',map);
    
        }
    
    
    
        public static int calculate(String s) {
            s = s.replaceAll("\\s+","");
            s += '#';
    
            Deque<Integer> numStack = new ArrayDeque<>();
            Deque<Character> opStack = new ArrayDeque<>();
            opStack.push('#');
    
            int i = 0;
            char ch = s.charAt(i);
    
    
            while (ch != '#' || opStack.peek() != '#') {
    
                if (!opSet.contains(ch)) {
                    while (ch == ' ') {
                        ch = s.charAt(++i);
                    }
                    int data = 0;
                    data = ch - '0';
    
                    ch = s.charAt(++i);
    
                    while (!opSet.contains(ch)) {
                        data = data * 10 + ch - '0';
                        ch = s.charAt(++i);
                    }
                    numStack.push(data);
                } else {
                    switch (compare(opStack.peek(), ch)) {
                        case '<':
                            opStack.push(ch);
                            ch = s.charAt(++i);
                            break;
    
                        case '=':
                            char x = opStack.pop();
                            ch = s.charAt(++i);
                            break;
    
                        case '>':
                            char op = opStack.pop();
                            Integer data2 = numStack.pop();
                            Integer data1 = numStack.pop();
                            int val = cal(data1, op, data2);
                            numStack.push(val);
                            break;
                    }
                }
            }
            int val = numStack.pop();
    
            return val;
        }
    
        private static int cal(Integer data1, char op, Integer data2) {
            switch (op){
                case '+': return data1+data2;
                case '-': return data1-data2;
                case '*': return data1*data2;
                case '/': return data1/data2;
                default: return 0;
            }
    
        }
    
        private static char compare(char op1, char op2) {
            return relation.get(op1).get(op2);
        }
    
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157

    最后

    我们都有光明的未来

    祝大家考研上岸
    祝大家工作顺利
    祝大家得偿所愿
    祝大家如愿以偿
    点赞收藏关注哦

  • 相关阅读:
    【数据结构】深入探讨二叉树的遍历和分治思想(一)
    navicate的安装使用
    熬了五年,马同学第一本书出版了!
    redis搭建主从、redis搭建集群、redis中StrictRedis()、RedisCluster()方法与python交互
    Phoenix创建Hbase二级索引_尚硅谷大数据培训
    Fabric.js 自由绘制圆形
    RK3568平台开发系列讲解(应用篇)串口应用编程之串口的使用步骤
    php lcg_value与mt_rand生成0~1随机小数的效果比较
    一篇文章带你掌握测试基础语言——Python
    STM32 中断详解
  • 原文地址:https://blog.csdn.net/qq_51625007/article/details/133255444