(Python, Java) 프로그래머스 - 숫자 문자열과 영단어

[문제 링크]

Python 풀이

def solution(s):
    answer = s
    words = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
    cnt = [0] * 10

    for idx in range(10):
        cnt[idx] = s.count(words[idx])

    for idx in range(10):
        for _ in range(cnt[idx]):
            answer = answer.replace(words[idx], str(idx))

    return int(answer)

Java 풀이

import java.util.HashMap;
import java.util.Map;

class Solution {
    public int solution(String s) {

        String[] numbers ={"zero","one","two","three","four","five","six","seven","eight","nine"};
        Map<String, String> map = new HashMap<>();
        int index =0;
        for (String number : numbers) {
            map.put(number,String.valueOf(index));
            index++;
        }

        for (String number : numbers) {
            s = s.replaceAll(number,map.get(number));
        }

        return Integer.valueOf(s);
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.solution("one4seveneight"));
    }
}

© 2021. By Backtony