Evaluate Reverse Polish Notation - LeetCode 150

題目描述:
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
Hide Tags Stack

分析:
逆波蘭式的計算規則如下:
如果是操作數,則直接壓入棧中,如果是運算符,則從棧中彈出兩個操作數進行運算後,將結果入棧。
本題的逆波蘭是的字符串數組,因此需要注意將字符串轉換爲整數,同時要注意負數的轉換。

以下是C++實現代碼

/*////////////////16ms//*/
class Solution {
public:
 bool isOp(string s) //判斷是否爲運算符
    {
        if(s == "+" || s == "-" || s == "*" || s == "/")
            return true;
        return false;
    }
    int stoi(string s) //將字符串轉換爲整數,注意負數
    {
	int flag = 1;
	int i = 0,num = 0;	
	if(s[0] == '-')
	{
	    flag = -1; //標記負數
	    i++;				
	} 
        while(i < s.size())
	{			
	    if(isdigit(s[i]))
		num = num * 10 + (s[i++] - '0');
	}		
        return flag * num;
    }

    int doOp(int a,int b,string op) //進行a op b運算
    {
        if(op == "+")
            return a + b;
        else if(op == "-")
            return a - b;
        else if(op == "*")
            return a * b;
        else if(op == "/")
            return a / b;		
        else ;
    }
    int evalRPN(vector<string>& tokens) {
        int len = tokens.size();
        //if(len == 1)
        //    return stoi(tokens[0]);
            
        stack<int> s;
        int i = 0;
		int num = 0;
        for(; i < len; i++)
        {
            if(!isOp(tokens[i]))
            {
                num = stoi(tokens[i]); //將操作數入棧
                s.push(num);
            }
            else //如果是運算符,就從棧中彈出兩個操作數,運算後將結果入棧
            {
                int a = 0,b = 0;
                b = s.top();
                s.pop();
                a = s.top();
                s.pop();
                s.push(doOp(a,b,tokens[i]));
            }
        }
        return s.top(); //最後棧裏只有一個元素,就是最終結果
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章