計算式【学習アルゴリズム】

序文

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());
    }
}

中置式の評価

インタビューの質問 16.26. 計算機

リートコード

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;
    }
}

アルゴリズム優先度分析

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);
    }

}


やっと

私たち全員に明るい未来があります

大学院受験の成功を祈り、
仕事での
成功を祈り、欲しいものを手に入れて
ください、いいね、集めて、フォローしてください。

おすすめ

転載: blog.csdn.net/qq_51625007/article/details/133255444