您的位置:首页 > 编程语言 > Lua

Leetcode 150:Evaluate Reverse Polish Notation

2015-05-02 15:57 603 查看
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


分析:

此题是逆波兰式的四则混合运算问题,算法如下:

1、构建空栈S。

2、遍历集合中得元素,如果是操作符op,则从栈中弹出两个元素S1, S2,计算S2 op S1的结果。

如果是操作数,则将其压入到栈S中。

代码如下,运算时间大约84ms。

class Solution {
public:
    int evalRPN(vector<string> &tokens) {
   	<span style="white-space:pre">	</span>if(tokens.size() == 0)
			return 0;
		string op[] = {"+", "-", "*", "/"};
		stack<int> mystack;
		map<string, int> op_map;
		for (int i = 0; i<sizeof(op)/sizeof(op[0]); i++)
		{
			op_map[op[i]] = i;
		}
		for (int i =0; i<tokens.size(); i++)
		{
			string c = tokens[i];
			if (op_map.count(c) != 0)
			{
				int num1 = mystack.top();
				mystack.pop();
				int num2 =mystack.top();
				mystack.pop();
				int num3;
				if (c == "+")
				{
					num3 = num1 + num2;
				} 
				else if (c == "-")
				{
					num3 = num2 - num1;
				}else if (c == "*"){
					num3 = num2 * num1;
				}
				else if(c == "/"){
					num3 = num2 /num1;
				}
				mystack.push(num3);
			}else{
				char *end;
				mystack.push(strtol(c.c_str(), &end, 10));
			}
		}
		return mystack.top();
          }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: