ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

https://programmers.co.kr/learn/courses/30/lessons/81301?language=java 

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์ˆซ์ž ๋ฌธ์ž์—ด๊ณผ ์˜๋‹จ์–ด

๋„ค์˜ค์™€ ํ”„๋กœ๋„๊ฐ€ ์ˆซ์ž๋†€์ด๋ฅผ ํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ๋„ค์˜ค๊ฐ€ ํ”„๋กœ๋„์—๊ฒŒ ์ˆซ์ž๋ฅผ ๊ฑด๋„ฌ ๋•Œ ์ผ๋ถ€ ์ž๋ฆฟ์ˆ˜๋ฅผ ์˜๋‹จ์–ด๋กœ ๋ฐ”๊พผ ์นด๋“œ๋ฅผ ๊ฑด๋„ค์ฃผ๋ฉด ํ”„๋กœ๋„๋Š” ์›๋ž˜ ์ˆซ์ž๋ฅผ ์ฐพ๋Š” ๊ฒŒ์ž„์ž…๋‹ˆ๋‹ค. ๋‹ค์Œ์€ ์ˆซ์ž์˜ ์ผ๋ถ€ ์ž

programmers.co.kr

[๋ฌธ์ œ ํ’€์ด]

- map์— ์˜๋‹จ์–ด๋ฅผ key๊ฐ’์œผ๋กœ ํ•˜๊ณ , Stringํ˜•์‹์˜ ์ˆซ์ž๋ฅผ value๋กœ ๊ฐ’์„ ๋„ฃ์–ด์ค๋‹ˆ๋‹ค.

- ๊ฐ ๋ฌธ์ž๋งˆ๋‹ค ๊ณ ์œ ์˜ ์‹๋ณ„๊ฐ’์„ ๋งŒ๋“ค์–ด์„œ lenMap์— ๊ธธ์ด๋ฅผ ์ €์žฅํ•ฉ๋‹ˆ๋‹ค.: ์˜๋‹จ์–ด์˜ ์•ž 2๊ธ€์ž๋ฅผ key๊ฐ’์œผ๋กœ ์‚ฌ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค.- String s๋ฅผ for๋ฌธ์œผ๋กœ ๋Œ๋ฉด์„œ ๋ณ€ํ™˜์„ ํ•ฉ๋‹ˆ๋‹ค.: ์ˆซ์ž๊ฐ€ ๋‚˜์˜จ๋‹ค๋ฉด ๊ทธ๋ž˜๋„ ์ €์žฅ: ๋ฌธ์ž๊ฐ€ ๋‚˜์˜จ๋‹ค๋ฉด lenMap์„ํ†ตํ•ด ๊ทธ ๊ธธ์ด๋งŒํผ ์ž๋ฅธ ์˜๋‹จ์–ด๋ฅผ map์— ๋„ฃ์–ด ๊ตฌํ•œ ์ˆซ์ž๋ฅผ ์ €์žฅ

[์ •๋‹ต ์ฝ”๋“œ]

import java.util.*;
class Solution {
    /*
    "on" ๋ฝ‘์Œ
    lenMap.get("on") = 3
    3๊ฐœ ์งœ๋ฅด๋ฉด "one"์–ป์Œ
    map.get("one") = "1"
    str์— 1๋ถ™์ž„
    */
    public static Map<String, String> map = new HashMap<>();
    public static Map<String, Integer> lenMap = new HashMap<>();
    public int solution(String s) {
        int answer = 0;
        String str = "";
        putMap();
        putLenMap();
        int index = 0;
        while(index < s.length()) {
            if(s.charAt(index) >= '0' && s.charAt(index) <= '9') {
                str += s.charAt(index);
                index++;
                //substring();
            } else {
                int len = lenMap.get(s.substring(index, index + 2));
                String key = s.substring(index, index + len);
                str += map.get(key);
                index += len;
            }
        }
        answer = Integer.parseInt(str);
        return answer;
    }
    // ์ˆซ์ž ๋ณ€ํ™˜๊ฐ’
    public static void putMap() {
        map.put("zero","0");
        map.put("one","1");
        map.put("two","2");
        map.put("three","3");
        map.put("four","4");
        map.put("five","5");
        map.put("six","6");
        map.put("seven","7");
        map.put("eight","8");
        map.put("nine","9");
    }
    // ๊ธธ์ด ์‹๋ณ„
    public static void putLenMap() {
        lenMap.put("ze",4);
        lenMap.put("on",3);
        lenMap.put("tw",3);
        lenMap.put("th",5);
        lenMap.put("fo",4);
        lenMap.put("fi",4);
        lenMap.put("si",3);
        lenMap.put("se",5);
        lenMap.put("ei",5);
        lenMap.put("ni",4);
    }
}