1. 程式人生 > >LeetCode 150. Evaluate Reverse Polish Notation

LeetCode 150. Evaluate Reverse Polish Notation

post ati spa solution 依次 進行 代碼 exp som

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

題目要求實現一種“逆波蘭表達式”,該表達式沒有括號表示優先級,優先級完全體現在順序中,從前到後掃描遇見符號就將符號前的兩個數進行對應運算,然後將此數入棧,依次進行,遍歷整個string向量。該題目為棧的典型應用

註意:1、盡量不要用switch語句,因為該語句支持吃 int 或者 char類型,使用if語句更好一些;2一定別忘處理只有vector中只有一個數字沒有運算符的情況

代碼如下:

 1 class Solution {
 2 public:
 3     int evalRPN(vector<string>& tokens) {
 4         int len = tokens.size();
 5         if (len == 1)
 6             return stoi(tokens[0].c_str());
 7         stack<int
> s; 8 for (int i = 0; i < len; i++) 9 { 10 if (tokens[i] != "+" && tokens[i] != "-" && tokens[i] != "*" && tokens[i] != "/") 11 s.push(atoi(tokens[i].c_str())); 12 else 13 { 14 int m = s.top();
15 s.pop(); 16 int n = s.top(); 17 s.pop(); 18 if (tokens[i] == "+") 19 s.push(n + m); 20 else if (tokens[i] == "-") 21 s.push(n - m); 22 else if (tokens[i] == "*") 23 s.push(n * m); 24 else 25 s.push(n / m); 26 } 27 28 } 29 return s.top(); 30 } 31 };

補充:c++11支持stoi函數,能直接將string轉化為int

LeetCode 150. Evaluate Reverse Polish Notation