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

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

样例

对于 [(5 − 6) * 7] 的表达式(该表达式可表示为["(", "5", "−", "6", ")", "*", "7"]),其对应的波兰表达式为 [* - 5 6 7](其返回的数值为["*", "−", "5", "6", "7"])。

class Solution {
public:
    /**
     * @param expression: A string array
     * @return: The Polish notation of this expression
     */
    vector<string> convertToPN(vector<string> &expression) {
        // write your code here
        int n = expression.size();
	    vector<string> result;
	    stack<string> operators;
	    stack<string> buf;
	    for (int i = n-1; i >= 0; i--)
	    {
		    if (expression[i].length() == 1 
			    && isOperator(expression[i]))
		    {
			    if (operators.empty())
			    {
				    operators.push(expression[i]);
			    }
			    else if (expression[i] == ")")
			    {
				    operators.push(expression[i]);
			    }
			    else if (expression[i] == "(")
			    {
				    while (operators.top() != ")")
				    {
					    buf.push(operators.top());
					    operators.pop();
				    }
				    operators.pop();
			    }
			    else
			    {
				    if (compare(expression[i], operators.top()))
				    {
					    operators.push(expression[i]);
				    }
				    else
				    {
					    while (!operators.empty() && !compare(expression[i], operators.top()))
					    {
						    buf.push(operators.top());
						    operators.pop();
					    }
					    operators.push(expression[i]);
				    }
			    }
		    }
		    else
		    {
			    buf.push(expression[i]);
		    }
	    }

	    while (!operators.empty())
	    {
		    buf.push(operators.top());
		    operators.pop();
	    }

	    while (!buf.empty())
	    {
		    result.push_back(buf.top());
		    buf.pop();
	    }

	    return result;
    }
private:
    bool compare(string &a, string &b)
    {
	    if (b == ")")
	    {
		    return true;
	    }
	    if (a == "*" || a == "/")
	    {
		    return true;
	    }
	    else if (b == "+" || b == "-")
	    {
		    return true;
	    }

	    return false;
    }
    
    bool isOperator(string &a)
    {
	    if (a == "+" || a == "-"
		    || a == "*" || a == "/"
		    || a == "(" || a == ")")
	    {   
		    return true;
	    }

	    return false;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值