ALGORITHM ๐Ÿค–/Programmers

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ๋Œ€์ถฉ ๋งŒ๋“  ์žํŒ

daxx0ne 2023. 4. 30. 14:54

https://school.programmers.co.kr/learn/courses/30/lessons/160586

import java.util.*;

class Solution {
    public int[] solution(String[] keymap, String[] targets) {
        int[] answer = new int[targets.length];
        Map<Character, Integer> pressCount = new HashMap<>(); // key: ๋ฌธ์ž, value: ์ตœ์†Œ ์ž…๋ ฅ ํšŸ์ˆ˜

        for (String key : keymap) { // ๊ฐ ๋ฌธ์ž๋ฅผ ์ž…๋ ฅํ•˜๊ธฐ ์œ„ํ•ด ํ‚ค๋ฅผ ๋ˆ„๋ฅด๋Š” ์ตœ์†Œ ํšŸ์ˆ˜๋ฅผ ๋งต์— ์ €์žฅ
            for (int i = 0; i < key.length(); i++) {
                char ch = key.charAt(i);
                if (!pressCount.containsKey(ch)) {
                    pressCount.put(ch, i + 1); // pressCount์— ํ•ด๋‹น ๋ฌธ์ž๊ฐ€ ์—†์œผ๋ฉด ์ƒˆ๋กœ ์ถ”๊ฐ€
                    continue;
                }
                if (pressCount.get(ch) > i) {
                    pressCount.replace(ch, i + 1); // ์ด๋ฏธ ์žˆ์œผ๋ฉด ์ž…๋ ฅ ํšŸ์ˆ˜๋ฅผ ๋น„๊ตํ•˜์—ฌ ๋” ์ ๊ฒŒ ๋ˆ„๋ฅด๋Š” ํšŸ์ˆ˜๋ฅผ ์ €์žฅ
                }
            }
        }

        for (int i = 0; i < targets.length; i++) { // ๊ฐ ๋ฌธ์ž์—ด์„ ๋งŒ๋“ค๊ธฐ ์œ„ํ•œ ์ตœ์†Œ ํšŸ์ˆ˜๋ฅผ ๊ณ„์‚ฐํ•˜์—ฌ answer์— ์ €์žฅ
            int sumTotal = 0;
            for (int j = 0; j < targets[i].length(); j++) {
                char ch = targets[i].charAt(j);
                if (!pressCount.containsKey(ch)) { // ํ•ด๋‹น ๋ฌธ์ž๊ฐ€ ์–ด๋””์—๋„ ์กด์žฌํ•˜์ง€ ์•Š์œผ๋ฉด -1์„ ์ฒซ๋ฒˆ์งธ ์ธ๋ฑ์Šค์— ์ €์žฅ
                    sumTotal = -1;
                    break;
                }
                sumTotal += pressCount.get(ch); // ๊ทธ๋ ‡์ง€ ์•Š๋‹ค๋ฉด, ํ•ด๋‹น ๋ฌธ์ž์˜ ์ž…๋ ฅ ํšŸ์ˆ˜๋ฅผ sumTotal์— ๋”ํ•ด์คŒ
            }
            answer[i] = sumTotal;
        }
        return answer;
    }
}