150. Evaluate Reverse Polish Notation
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> s = new Stack<Integer>();
Set<String> op = new HashSet<String>();
if (tokens.length == 1) {
return Integer.valueOf(tokens[0]);
}
op.add("+");
op.add("-");
op.add("*");
op.add("/");
int i = 0;
while (i < tokens.length) {
if (op.contains(tokens[i])) {
int sec = s.pop();
int first = s.pop();
if (tokens[i].equals("+")) {
s.push(first + sec);
} else if (tokens[i].equals("-")) {
s.push(first - sec);
} else if (tokens[i].equals("*")) {
s.push(first * sec);
} else if (tokens[i].equals("/")) {
s.push(first / sec);
}
} else {
s.push(Integer.valueOf(tokens[i]));
}
i++;
}
return s.pop();
}
}
Runtime: 6 ms, faster than 23.34% of Java online submissions for Evaluate Reverse Polish Notation.
Memory Usage: 41.4 MB, less than 5.88% of Java online submissions for Evaluate Reverse Polish Notation.
오랜만에 제 힘으로 풀었읍니다^^
답지에서 stack을 사용했는데 훨씬 더 깔끔한 방식
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (String token : tokens) {
if (!"+-*/".contains(token)) {
stack.push(Integer.valueOf(token));
continue;
}
int number2 = stack.pop();
int number1 = stack.pop();
int result = 0;
switch (token) {
case "+":
result = number1 + number2;
break;
case "-":
result = number1 - number2;
break;
case "*":
result = number1 * number2;
break;
case "/":
result = number1 / number2;
break;
}
stack.push(result);
}
return stack.pop();
}
}
class Solution {
private static final Map<String, BiFunction<Integer, Integer, Integer>> OPERATIONS = new HashMap<>();
// Ensure this only gets done once for ALL test cases.
static {
OPERATIONS.put("+", (a, b) -> a + b);
OPERATIONS.put("-", (a, b) -> a - b);
OPERATIONS.put("*", (a, b) -> a * b);
OPERATIONS.put("/", (a, b) -> a / b);
}
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (String token : tokens) {
if (!OPERATIONS.containsKey(token)) {
stack.push(Integer.valueOf(token));
continue;
}
int number2 = stack.pop();
int number1 = stack.pop();
BiFunction<Integer, Integer, Integer> operation;
operation = OPERATIONS.get(token);
int result = operation.apply(number1, number2);
stack.push(result);
}
return stack.pop();
}
}
Bifunction이라고 잘난척 해놓으신ㅠ
Author And Source
이 문제에 관하여(150. Evaluate Reverse Polish Notation), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@jwade/150.-Evaluate-Reverse-Polish-Notation저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)