My code:
public class Solution {
public int evalRPN(String[] tokens) {
if (tokens == null || tokens.length == 0) {
return -1;
}
Stack<Integer> st = new Stack<Integer>();
for (int i = 0; i < tokens.length; i++) {
String token = tokens[i];
if (token.charAt(token.length() - 1) >= '0' && token.charAt(token.length() - 1) <= '9') {
st.push(Integer.parseInt(token));
}
else {
Integer right = st.pop();
Integer left = st.pop();
int result = 0;
if (token.equals("+")) {
result = left + right;
}
else if (token.equals("-")) {
result = left - right;
}
else if (token.equals("*")) {
result = left * right;
}
else {
result = left / right;
}
st.push(result);
}
}
return st.pop();
}
}
一开始以为是复杂题目,后来仔细看了下,发现是简单题。
Anyway, Good luck, Richardo! — 09/16/2016