Post

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

영어 숫자 단어가 공백 없이 이어진 문자열을 정수로 바꿔 반환하는 문제.

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

문제 링크


1. 아이디어

문자열은 zero부터 nine까지의 영어 숫자 단어가 공백 없이 이어져 만들어지므로, 각 단어를 대응하는 숫자로 치환한 뒤 정수로 변환하면 된다. 열 개의 단어는 어느 하나도 다른 단어의 부분 문자열이 아니고, 치환 결과가 숫자라서 치환 도중 새로운 단어가 생기지도 않는다. 따라서 어떤 순서로 치환하든 결과는 같다.


2. 복잡도

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

($N$ = numbers의 길이)


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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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.