华为机试题:仿LISP

package com.nowcoder.huawei;

import java.util.*;

public class LISP {
    // 只通过80%
    // (+ (* 2 3) (^ 4))
    // (+ (* 2 3) (^ 4))(2 3)
    // ((+ 2 3)
    // ((+ 2 3))
    // (^ (+ (* 2 3) (^ ((^ 4)))))
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String express = scanner.nextLine();

        Stack stack = new Stack<>();
        for (int i = 0; i < express.length(); i++) {
            char c = express.charAt(i);
            if (c == ')') {
                StringBuilder builder = new StringBuilder();
                char top;
                while (!stack.empty() &&(top = stack.pop()) != '(') {
                    builder.append(top);
                }

                String currExp = builder.reverse().toString();
//                System.out.println(currExp);

                String[] ops = currExp.split(" ");
                if (ops.length == 2) {
                    int value = Integer.valueOf(ops[1]);
                    value++;
                    String count = String.valueOf(value);
                    for (int j = 0; j < count.length(); j++) {
                        stack.push(count.charAt(j));
                    }
                } else if (ops.length == 3) {
                    int a = Integer.valueOf(ops[1]);
                    int b = Integer.valueOf(ops[2]);
                    int value = 0;
                    switch (ops[0]) {
                        case "+":
                            value = a + b;
                            break;
                        case "*":
                            value = a * b;
                            break;
                    }
                    String count = String.valueOf(value);
                    for (int j = 0; j < count.length(); j++) {
                        stack.push(count.charAt(j));
                    }
                } else if (ops.length == 1) {
                    for (int j = 0; j < ops[0].length(); j++) {
                        stack.push(ops[0].charAt(j));
                    }
                }

            } else {
                stack.push(c);
            }
        }

        StringBuilder builder = new StringBuilder();
        while (!stack.empty())
            builder.append(stack.pop());

        try {
            System.out.println(Integer.valueOf(builder.reverse().toString()));
        } catch (Exception e) {
            System.out.println(-1);
        }
    }
}

 

转载于:https://www.cnblogs.com/bigdata-stone/p/11297179.html

你可能感兴趣的:(华为机试题:仿LISP)