Baseball Game
2020.12.22
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 ofx
."+"
- 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.์๋ฃ๊ตฌ์กฐ : Stack

์๊ณ ๋ฆฌ์ฆ 1. ์ ์ํ Stack์ ๋ง๋ ๋ค.
Stack<Integer> stack = new Stack<>();
2. ๋ฐ๋ณต๋ฌธ ์์ฑ : default๋ฌธ์ผ๋ก ์ธํ String์ ์ซ์ ์์๋ค์ ๋ค ๋ฃ๋๋ค. ์ธํ String์ด ๋ฌธ์ ์์๋ฉด ๊ทธ์ ํด๋นํ๋ ์ฐ์ฐํ๋ค. - stack.pop(), stack.peek(), stack.push() ์ด์ฉ
for(String str : ops) {
if(str == "C") {//์์ ์์ ์ญ์ }
if(str == "D") {//์์ ์์ 2๋ฐฐ}
if(str == "+") {//์์ ์์ 2๊ฐ ๋ง์
}
stack.push(Integer.valueOf(str));
}
3. Stack์ ๋ฐ์ดํฐ๋ฅผ ๋ค ๋ํด์ ๋ฆฌํดํ๋ค.
์๊ณ ๋ฆฌ์ฆ์ Java๋ก ๊ตฌํ
public class BaseballGame {
public static void main(String[] args) {
String[] strs = {"5","-2","4","C","D","9","+","+"};
System.out.println(calPoints(strs));
}
public static int calPoints(String[] ops) {
Stack<Integer> stack = new Stack<>();
for (String op : ops) {
switch (op) {
case "+":
int x = stack.pop();
int y = stack.pop();
stack.push(y);
stack.push(x);
stack.push(x + y);
break;
case "D":
stack.push(stack.peek() * 2);
break;
case "C":
stack.pop();
break;
default:
stack.push(Integer.valueOf(op));
}
}
int sum = 0;
while (!stack.isEmpty()) {
sum += stack.pop();
}
return sum;
}
}
๋ฐฐ์ด ๋ด์ฉ 1. switch๋ฌธ๊ณผ case๋ฌธ ์ด์ฉ
for(String str : ops) {
switch(str) {
case "+" :
int x = stack.pop();
int y = stack.pop();
stack.push(y);
stack.push(x);
stack.push(x+y);
break;//?
case "D" :
stack.push(stack.pop()*2);
break;
case "C" :
stack.pop();
break;
dafualt:
stack.push(Integer.valueOf(str));
}
2. String์ Integer๋ก ๋ฐ๊พธ๋ ๋ฐฉ๋ฒ
Integer.valueOf(String);
Integer.parseInt(String);
3. String ๋ฐฐ์ด์ ๊ธธ์ด : StringArray.length
Last updated
Was this helpful?