每日AC

来源:互联网 发布:c语言进制转换程序 编辑:程序博客网 时间:2024/05/17 01:24


每日AC  - 后缀表达式计算结果-leetcode-evaluate-reverse-polish-notation

题目描述


Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are+,-,*,/. Each operand may be an integer or another expression.

Some examples:

  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6


昨日在地铁上看《大话数据结构》回顾下大学时光, 这个逆波兰, 有机会再奉献一份 中缀表达式变后缀的算法


后缀表达式 计算结果,抓住, 符号前来两个必须是数字, 才可以进行计算  == equals 不能乱用


AC 代码:

import java.util.Stack;/** * 类说明 *  * <pre> * Modify Information: * Author        Date          Description * ============ =========== ============================ * DELL          2017年6月21日    Create this file * </pre> *  */public class EvalRPN {    /**     * 您的代码已保存 答案错误:您提交的程序没有通过所有的测试用例 case通过率为0.00%     *      * 测试用例: ["0","3","/"]     *      * 对应输出应该为:     *      * 0     *      * 你的输出为:     *      * java.util.EmptyStackException     *      * 但是本地IDE运行没问题 ,最好的方式是将 == 变成 equals      * @param tokens     * @return     */    public int evalRPN(String[] tokens) {        int result = 0;        Stack<String> s= new Stack<String>();        for(int i = 0; i <tokens.length ;i++){            if(tokens[i].equals("+") || tokens[i].equals("-") ||tokens[i].equals("*") ||tokens[i].equals("/")){                int first =Integer.parseInt(s.pop());                int second = Integer.parseInt(s.pop());                int cop = 0;                if(tokens[i].equals("+")){                    cop = first+second;                    s.push(cop+"");                } else if(tokens[i].equals("-")){                    cop = second - first;                    s.push(cop+"");                }else if(tokens[i].equals("/")){                    cop = second/first;                    s.push(cop+"");                } else if(tokens[i].equals("*")){                    cop = second*first;                    s.push(cop+"");                }            }else{                s.push(tokens[i]);            }        }        result = Integer.parseInt(s.pop());                return result;            }    /**     * @param args     */    public static void main(String[] args) {        String[] str = { "2", "1", "+", "3", "*" };        String[] str1 = { "4", "13", "5", "/", "+" };        String[] str2 = { "0", "3", "/" };        int ans = new EvalRPN().evalRPN(str2);        System.out.println(ans);    }}


原创粉丝点击