Post

[Programmers] #120853 - 컨트롤 제트 [Java][C++][Python]

숫자와 Z로 이뤄진 문자열에서 Z가 나올 때마다 직전 숫자를 취소하며 전체 합을 구하는 문제.

[Programmers] #120853 - 컨트롤 제트 [Java][C++][Python]

문제 링크


1. 아이디어

문자열을 공백으로 나눠 토큰을 앞에서부터 훑는다. 토큰이 숫자면 합에 더하고, Z면 직전에 더한 숫자를 다시 뺀다.

Z는 문자열 맨 앞에 오지 않고 연속으로 등장하지도 않으므로, Z를 만난 시점에서 마지막으로 더한 값은 항상 바로 앞 토큰이다. 따라서 되돌릴 값을 스택으로 따로 들고 있을 필요 없이 이전 토큰을 다시 파싱해 빼면 된다.


2. 복잡도

접근시간공간
풀이$O(N)$$O(N)$

($N$ = s의 길이)


3. 코드

풀이 [Java][C++][Python]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
    public int solution(String s) {
        String[] arr = s.split(" ");
        int sum = 0;

        for (int i = 0; i < arr.length; i++) {
            if (arr[i].equals("Z")) {
                sum -= Integer.parseInt(arr[i - 1]);
            } else {
                sum += Integer.parseInt(arr[i]);
            }
        }

        return sum;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <bits/stdc++.h>
using namespace std;

int solution(string s) {
    vector<string> v;
    stringstream ss(s);
    string token;
    while (ss >> token) v.push_back(token);

    int sum = 0;
    for (int i = 0; i < v.size(); i++) {
        if (v[i] == "Z") {
            sum -= stoi(v[i - 1]);
        } else {
            sum += stoi(v[i]);
        }
    }

    return sum;
}
1
2
3
4
5
6
7
8
9
10
11
def solution(s):
    lst = s.split()
    total = 0

    for i in range(len(lst)):
        if lst[i] == "Z":
            total -= int(lst[i - 1])
        else:
            total += int(lst[i])

    return total

This post is licensed under CC BY 4.0 by the author.