본문 바로가기
Algorithm/leetcode

[leetcode] 682.Baseball Game

by 세류오 2023. 8. 19.

https://leetcode.com/problems/baseball-game/description/

 

Baseball Game - LeetCode

Can you solve this real interview question? Baseball Game - You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record. You are given a list of strings operations, where operations[i] is

leetcode.com

 

 

Stack을 이용

정직하게 설명되어있는 대로 구현만 하면 되는 문제

pop과 push를 이용하여 풀이

어렵지는 않았지만 "+"처리 중 pop이후 push하는 순서를 햇갈려서

시간을 많이 잡아먹었다.

 

import java.util.*;
class Solution {
    public int calPoints(String[] operations) {
        
        Stack<Integer> st = new Stack<>();

        if(1 <= operations.length && 1000 >= operations.length){
            for(String s : operations){
                //Record a new score that is the sum of the previous two scores.
                if(s.equals("+")){
                    int num01 = st.pop();
                    int num02 = st.pop();
                    //remind Stack is LIFO
                    st.push(num02);
                    st.push(num01);
                    st.push(num01 + num02);
                }
                //Record a new score that is the double of the previous score.
                else if(s.equals("D")){
                    int num01 = st.pop();

                    st.push(num01);
                    st.push(num01 * 2);
                }

                //Invalidate the previous score, removing it from the record
                else if(s.equals("C")){
                    st.pop();
                }
                else{
                    st.push(Integer.parseInt(s));
                }
            }
        }

        int sum = 0;
        while (!st.isEmpty()) {
            sum += st.pop();
        }
        return sum;
    }
}