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

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

样例

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

class Solution {
public:
    /**
     * @param expression: A string array
     * @return: The Reverse Polish notation of this expression
     */
    vector<string> convertToRPN(vector<string> &expression) {
        // write your code here
        int n = expression.size();
	    vector<string> result;
	    stack<string> operators;
	
	    for (int i = 0; i < n; 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() != "(")
				    {
					    result.push_back(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()))
					    {
						    result.push_back(operators.top());
						    operators.pop();
					    }
					    operators.push(expression[i]);
				    }
			    }
		    }
		    else
		    {
			    result.push_back(expression[i]);
		    }
	    }

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

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

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

	    return false;
    }
};


你可能感兴趣的:(将表达式转换为逆波兰表达式)