LeetCode_150evalRPN [Evaluate Reverse Polish No..]

#include <cstdio>
#include <algorithm>
#include <vector>
#include <string>
#include <stack>
using namespace std;

class Solution {
public:
	// 参考:http://zh.wikipedia.org/wiki/逆波兰表示法 即可
	int evalRPN(vector<string> &tokens) {
		stack<int> stk;
		for (int i = 0; i < tokens.size(); ++i) {
			string word = tokens[i];
			char ch = word[0];
			if (word.size() > 1 || isdigit(ch))
				stk.push(str2int(word));
			else {
				int val2 = stk.top(); stk.pop();
				int val1 = stk.top(); stk.pop();
				if (ch == '+') stk.push(val1 + val2);
				else if (ch == '-') stk.push(val1 - val2);
				else if (ch == '*') stk.push(val1 * val2);
				else if (ch == '/') stk.push(val1 / val2);
			}
		}
		return stk.top();
	}

	int str2int(string& s) {
		int res = 0, flag = 1, i = 0;
		if (!isdigit(s[0])) {
			flag = s[0] == '+' ? 1 : -1;
			++i;
		}
		for (; i < s.size(); ++i)
			res = res * 10 + (s[i] - '0');
		return res*flag;
	}
};



你可能感兴趣的:(LeetCode,reverse,notation,evaluate,Polish)