본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 682. Baseball Game

반응형

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을 이용한 구현 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

원소의 전체합을 구하는 변수 sum과 stack st를 선언해줍니다.

📔 풀이과정

1. operation들의 원소를 순회합니다.2. 정해진 연산에 따라 분기를 나눠 구현해줍니다. "+"의 경우 stack에서 한개를 빼 위에서 두 번째 원소를 알아낸 뒤 top이었던 원소를 다시 push하고 첫 번째와 두 번째를 더한 값을 다시 push해줘야 합니다.3. st의 원소들을 모두 sum에 더해줍니다.

📔 정답 출력 | 반환

sum을 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    int calPoints(vector<string>& operations) {
        int sum = 0;
        stack <int> st;
        for(auto o : operations) {
            if(o == "+") {
                int prev = st.top();
                st.pop();
                int prevv = st.top();
                st.push(prev);
                st.push(prev + prevv);
            }
            else if(o == "D") {
                st.push(st.top() * 2);
            }
            else if(o == "C") {
                st.pop();
            }
            else {
                st.push(stoi(o));
            }
        }

        while(st.size()) {
            sum += st.top();
            st.pop();
        }
            
        return sum;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.