将表达式转换为逆波兰表达式

时间:2025-03-27 13:52:52

给定一个表达式字符串数组,返回该表达式的逆波兰表达式(即去掉括号)

样例

对于 [3 - 4 + 5]的表达式(该表达式可表示为["3", "-", "4", "+", "5"]),返回[3 4 - 5 +](该表达式可表示为 ["3", "4", "-", "5", "+"])。

思路:

看注释

class Solution {
    /**
     * @param expression: A string array
     * @return: The Reverse Polish notation of this expression
     */
    public ArrayList<String> convertToRPN(String[] expression) {
        // write your code here
        ArrayList<String> R = new ArrayList<String>();//如果传入的表达式的长度为0或1直接返回
        if(==0)
            return R;
        else if(==1){
            (expression[0]);
            return R;
        }
        Stack<String> tokens = new Stack<String>();//用栈存储符号
        String now = null;
        
        for(int i=0;i<;++i){
            now = expression[i];
            if(("[-]?\\d+")){//如果为数字,直接计入
                    (now);
            }else if(()){
/*
*对于符号,若当前的符号的优先级比栈顶的符号高或栈为空,压入栈中。否则把栈中符号弹出,直至当前的符号的优先级比栈顶的符号高或者栈为空
*在压入栈中
*/
                    (now);
            }else if(("+")||("-")){
                while(!()&&(!().equals("("))){
                    (());
                }
                (now);
            }else if(("*")||("/")){
                while(!()&&
                    (().equals("*")||().equals("/"))){
                    (());
                }
                (now);
            }else if(("(")){
                (now);
            }else if((")")){
                while(!()&&(!().equals("("))){
                    (());
                }
                ();
            }
        }
        while(!())
            (());
        return R;
    }
}