Post

[Programmers] #120894 - 영어가 싫어요 [Java][C++][Python]

[Programmers] #120894 - 영어가 싫어요 [Java][C++][Python]

문제 링크


1. 아이디어

문자열 numbers는 zero부터 nine까지의 영어 숫자 단어 조합이 공백 없이 이어져 있다. zero부터 nine까지 각 문자열을 0부터 9까지의 문자열로 치환하면 numbers를 result로 깔끔하게 변환할 수 있다.


2. 복잡도

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

($N$ = numbers의 길이. C++는 find로 매번 처음부터 다시 탐색하고 replace로 구간을 밀어내 시간 $O(N^2)$, 인자로 받은 numbers 사본을 제자리 수정해 공간 $O(1)$)


3. 코드

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
    public long solution(String numbers) {
        numbers = numbers
                .replace("zero", "0")
                .replace("one", "1")
                .replace("two", "2")
                .replace("three", "3")
                .replace("four", "4")
                .replace("five", "5")
                .replace("six", "6")
                .replace("seven", "7")
                .replace("eight", "8")
                .replace("nine", "9");

        return Long.parseLong(numbers);
    }
}

zero부터 nine까지 각 단어를 대응하는 숫자로 바꾸는 replace 메서드를 이어붙였다. replace는 문자열에 등장하는 해당 부분 문자열을 모두 바꾼 새 문자열을 반환하므로, 메서드 체이닝을 통해 열 번의 호출이면 모든 단어가 잘 치환된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <bits/stdc++.h>
using namespace std;

string words[10] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};

long long solution(string numbers) {
    for (int d = 0; d < 10; d++) {
        int pos;
        while ((pos = numbers.find(words[d])) != -1) {
            numbers.replace(pos, words[d].size(), to_string(d));
        }
    }

    return stoll(numbers);
}

인덱스가 그 단어가 나타내는 숫자가 되는 words 배열을 먼저 만들었다. 각 단어에 대해 find로 등장 위치를 찾을 때마다 replace로 그 구간(words[d].size() 길이)을 숫자 문자열로 바꾸고, find가 더는 위치를 반환하지 않을 때까지(= -1) 반복해 같은 단어가 여러 번 나와도 모두 처리했다.

1
2
3
4
5
6
def solution(numbers):
    words = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
    for d, w in enumerate(words):
        numbers = numbers.replace(w, str(d))

    return int(numbers)

인덱스가 그 단어가 나타내는 숫자가 되는 words 리스트를 먼저 만들었다. enumerate로 (숫자, 단어) 쌍을 돌며 replace로 그 단어를 전부 해당 숫자 문자로 바꾼 뒤 int로 정수로 변환했다. replace가 매칭되는 부분을 모두 바꾸므로 단어당 한 번의 호출로 모든 단어를 처리할 수 있다.


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