반응형
https://leetcode.com/problems/baseball-game/description/
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;
}
};
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > Implementation' 카테고리의 다른 글
(C++) - LeetCode (easy) 709. To Lower Case (0) | 2023.06.21 |
---|---|
(C++) - LeetCode (easy) 693. Binary Number with Alternating Bits (0) | 2023.06.13 |
(C++) - LeetCode (easy) 671. Second Minimum Node In a Binary Tree (0) | 2023.06.09 |
(C++) - LeetCode (easy) 661. Image Smoother (0) | 2023.06.05 |
(C++) - LeetCode (easy) 657. Robot Return to Origin (0) | 2023.06.02 |