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

[Leetcode][JAVA] Evaluate Reverse Polish Notation

2014-09-10 04:45 537 查看
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

使用栈即可实现。遇到运算符号即pop出俩数运算,否则push
由于测试用例没有非法的表达式,所以很容易即可ACCEPT
public int evalRPN(String[] tokens) {
Stack<String> st = new Stack<String>();
for(int i=0;i<tokens.length;i++)
{
String t = tokens[i];
if(t.equals("+") || t.equals("-") || t.equals("*") || t.equals("/"))
{
int x2 = Integer.parseInt(st.pop());
int x1 = Integer.parseInt(st.pop());
if (t.equals("+"))
st.push(String.valueOf(x1 + x2));
else if (t.equals("-"))
st.push(String.valueOf(x1 - x2));
else if (t.equals("*"))
st.push(String.valueOf(x1 * x2));
else
st.push(String.valueOf(x1 / x2));
}
else
st.push(t);
}

return Integer.parseInt(st.pop());
}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: