LintCode 369: Convert Expression to Polish Notation (波兰表达式,栈经典题)

  1. Convert Expression to Polish Notation
    中文English
    Given a string array representing an expression, and return the Polish notation of this expression. (remove the parentheses)

Example
Example 1:

Input: ["(", “5”, “-”, “6”, “)”, “", “7”]
Output: ["
”, “-”, “5”, “6”, “7”]
Explanation: (5 - 6) * 7 = -1 * 7 = -7
* - 5 6 7 = * -1 7 = -7
Example 2:

Input: [“3”, “+”, “(”, “1”, “-”, “2”, “)”]
Output:["+", “3”, “-”, “1”, “2”]
Explanation: 3 + (1 - 2) = 3 + -1 = 2
+ 3 - 1 2 = + 3 -1 = 2
Clarification
Definition of Polish Notation:

http://en.wikipedia.org/wiki/Polish_notation
http://baike.baidu.com/view/7857952.htm

解法1:用stack
类似LIntCode370 逆波兰序列那题。不过是反过来读。最后把结果倒序即可。

代码如下:

class Solution {
public:
    /**
     * @param expression: A string array
     * @return: The Polish notation of this expression
     */
    vector<string> convertToPN(vector<string> &expression) {
        int n = expression.size();
        stack<string> st;
        map<string, int> mp; //operator, priority
        vector<string> result;
        string topStr;
        mp["+"] = 1;
        mp["-"] = 1;
        mp["*"] = 2;
        mp["/"] = 2;
        
        for (int i = n - 1; i >= 0; --i) {
            string str = expression[i];
            if (str.size() > 1 || isdigit(str[0])) 
                result.push_back(str);
            else if (str == ")") 
                st.push(str);
            else if (str == "(") {
                while(st.top() != ")") {
                    topStr = st.top();
                    st.pop();
                    result.push_back(topStr);
                }
                st.pop();
            } else { //+-*/
               
                while(!st.empty() && (!isOperator(str) || mp[st.top()] > mp[str])) {
                    topStr = st.top();
                    st.pop();
                    result.push_back(topStr);            
                }
                st.push(str);
            }
                
        }
        
        while(!st.empty()) {
            topStr = st.top();
            st.pop();
            result.push_back(topStr);
        }
        
        reverse(result.begin(), result.end());
        
        return result;
    }
private:
    bool isOperator(string s) {
        return (s.size() == 1 && !isdigit(s[0]));
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值