Post

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

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

문제 링크


1. 아이디어

영어 단어로 적힌 숫자를 정수로 바꾸는 문제로, 단어를 대응하는 숫자로 치환한 뒤 정수로 읽는다. 단어는 공백 없이 이어져 있지만 이웃한 두 단어가 경계에서 겹쳐 다른 단어 모양을 만들지 않으므로 어느 순서로 치환해도 결과가 같다. 맨 앞에 zero가 오지 않아 치환 뒤 앞자리가 0이 되는 일이 없고, 길이가 50 이하라 숫자가 최대 16자리까지 나와 32비트 정수에는 담기지 않는다.


2. 코드

풀이 [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);
    }
}
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);
}

find가 못 찾으면 반환하는 std::string::npos는 int에 담으면 -1이 되므로 != -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)

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