java - 计算逆波兰表示法中算术表达式的值

标签 java string stack postfix-mta

我们给出了字符串数组,其中包含后缀表达式作为其元素,我们需要进行评估

我尝试使用堆栈但遇到异常: 线程“main”中的异常 java.util.EmptyStackException

public int evalRPN(String[] A) {

     Stack<Integer> s=new Stack<>();
     int i=0;
     while(s.isEmpty()==false && i<A.length)
     {
        String p=A[i++];
        if(p.matches("\\d"))
            s.push(Integer.parseInt(p));
        else
            {
                int a=s.pop();
                int b=s.pop();

                switch(p)
                {
                    case "+": s.push(b+a);break;
                    case "-": s.push(b-a);break;
                    case "*": s.push(b*a);break;
                    case "/": s.push(b/a);break;


                }
            }

    }
    return s.pop();
 }

最佳答案

public int evalRPN(String[] A) {

     Stack<Integer> s=new Stack<>();
     int i=0;
     while(i<A.length) //stack will be empty right at the start.. no need to check this
     {
        String p=A[i++];
        if(p.matches("\\d")) //I am not quite sure, but this just matches single digits, right? I would go for "\\d*", but I am not completely sure. Anyways you won't capture negative values or decimals.. perhaps better exclude +-*/ and use Double.parseDouble and a Stack<Double>
            s.push(Integer.parseInt(p));
        else
            {
                int a=s.pop();
                int b=s.pop();

                switch(p)
                {
                    case "+": s.push(b+a);break;
                    case "-": s.push(b-a);break;
                    case "*": s.push(b*a);break;
                    case "/": s.push(b/a);break;


                }
            }

    }
    return s.pop();
 }

如果给定的表达式不正确(运算符太多/操作数太少),这可能会遇到错误,或者可能只返回中间结果(操作数太多/运算符太少)。

关于java - 计算逆波兰表示法中算术表达式的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57930780/

相关文章:

java - 如何确定我的服务器可以支持特定应用程序的用户数量

java - 没有 XML 的 Spring + Hibernate。错误 : NoSuchBeanDefinitionException

string - Swift - 用空格替换字符串中的表情符号

python - 为什么使用 for 循环将 '\n' 存储为一项?

flutter - 如何在 Dart 中实现带有 push 和 pop 的堆栈

java - 反转数组中的元素,并使用单个 for 循环将反转后的元素压入堆栈

java - 时间和第二期显示 1 :10 instead of 13:10

java - 想要用java创建验证码

c++ - 如何检查 stringstream>>string 是否不会在字符串上放置任何内容?

java - 将 Queue 和 Stack 相互复制