https://leetcode.com/problems/baseball-game/
You are keeping score for a baseball game with strange rules. The game consists of several rounds, where the scores of past rounds may affect future rounds' scores.
At the beginning of the game, you start with an empty record. You are given a list of strings ops, where ops[i] is the ith operation you must apply to the record and is one of the following:
An integer x - Record a new score of x.
"+" - Record a new score that is the sum of the previous two scores. It is guaranteed there will always be two previous scores.
"D" - Record a new score that is double the previous score. It is guaranteed there will always be a previous score.
"C" - Invalidate the previous score, removing it from the record. It is guaranteed there will always be a previous score.
Return the sum of all the scores on the record.
$$ 1 <= ops.length <= 1000$$
is "C", "D", "+", or a string representing an integer in the range
For operation "+", there will always be at least two previous scores on the record.
For operations "C" and "D", there will always be at least one previous score on the record.
'+'를 제외하고는 전부 최근 마지막 순서의 숫자만 건드리는 것을 보고 스택을 이용하여 풀었다. 정답인 합계를 스택을 for문을 돌려서 계산하려했다가 그때그때 체크하는 것이 가능해보여서 answer라는 int 변수를 선언하여 더 빠를것 같은 방법으로 작성했다.
import java.util.Stack;
class Solution {
public int calPoints(String[] ops) {
Stack<Integer> stack = new Stack<>();
int answer = 0;
for (String op : ops) {
switch (op) {
case "C":
answer -= stack.pop();
break;
case "D":
int tmp = stack.peek() * 2;
stack.push(tmp);
answer += tmp;
break;
case "+":
int last = stack.pop(), sum = stack.peek() + last;
stack.push(last);
stack.push(sum);
answer += sum;
break;
// 숫자는 stack에 넣기
default:
int n = Integer.parseInt(op);
stack.push(n);
answer += n;
}
}
return answer;
}
}