Deep_Dev

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

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

 


๋จผ์ € ์‹ ๊ฒฝ์“ด ๋ถ€๋ถ„์€ ์ฐพ์„ target๋ฌธ์ž์—ด์ค‘ ๋ฌธ์ž๊ฐ€ ๋งŒ์•ฝ์— ์—†๋‹ค๋ฉด -1 ๋กœ ๋๋‚˜๋Š”๊ฒƒ์ด๋‹ค.

 

๊ทธ๋ž˜์„œ keymap์˜ ๋ฌธ์ž์—ด์„ ๋ชจ๋‘ ๋”ํ•ด์„œ, ์ฐพ์„ ์ˆ˜ ์žˆ๋Š”์ง€ ์—†๋Š”์ง€ ๋จผ์ € ํŒ๋ณ„ํ–ˆ๋‹ค.

 

๊ทผ๋ฐ ๊ณ„์† ์˜ค๋‹ต์ด ๋‚˜์™”๋˜๊ฒŒ .. ! 

keymap ์ „์ฒด ๋ฐฐ์—ด์ค‘ ์ฐพ์„์ˆ˜๋Š” ์žˆ์–ด์„œ indexOf๋กœ ์ˆœ์ฐจ์ ์œผ๋กœ ๊ฐ€์žฅ ์ž‘์€ ์ˆ˜์˜ index๋ฅผ ๊ตฌํ•˜๋Š”๋ฐ

 

keymap[0] ์—์„œ๋Š” ํ•ด๋‹น ๋ฌธ์ž๊ฐ€ ์žˆ๊ณ 

keymap[1] ์—๋Š” ์—†์„๊ฒฝ์šฐ 0์ด๋ผ๋Š” ์ œ์ผ ์ž‘์€ index๋ฅผ ๋ฐ›์•„๋„ ๋‹ค์Œ ๋น„๊ต ์ธ๋ฑ์Šค์—์„œ -1๊ณผ ๋น„๊ตํ•ด์„œ 

-1๋กœ ๋๋‚˜๊ฒŒ ๋˜๊ณ , ๋ˆ„๋ฅธ ํšŸ์ˆ˜๋Š” index + 1๋กœ ๊ตฌ์„ฑํ–ˆ๊ธฐ๋•Œ๋ฌธ์— ์ž๊พธ answer์— 0์ด ๋“ค์–ด๊ฐ”๋‹ค..

 

๋ฌด์Šจ ๋ง์ธ์ง€ ์งง๊ฒŒ ์„ค๋ช…ํ–ˆ์ง€๋งŒ ์กฐ๊ธˆ ๋” ๊ตฌ์ฒด์ ์ธ๊ฑด ์ฃผ์„์œผ๋กœ ๋‹ฌ์•˜์Œ.

 

import java.util.*;

class Solution {
    public int[] solution(String[] keymap, String[] targets) {
        int[] answer = new int[targets.length];

        // ๋ฌธ์ž์—ด์˜ ํ•ฉ
        String totalString = "";
        for (int i = 0; i < keymap.length; i++) {
            totalString += keymap[i];
        }

        int cnt = 0;
        for (int i = 0; i < targets.length; i++) {
            cnt = 0;
            for (int j = 0; j < targets[i].length(); j++) {
                char ch = targets[i].charAt(j);
                // ์ฐพ์„ target๋ฌธ์ž๊ฐ€ ์•„์˜ˆ ์—†๋‹ค๋ฉด -1ํ•˜๊ณ  ๋‹ค์Œ๋ฌธ์ž๋กœ
                if (!totalString.contains(String.valueOf(ch))) {
                    answer[i] = -1;
                    break;
                }
                int maxIndex = 999;
                // ์ฐพ์„ target ๋ฌธ์ž๊ฐ€ keymap์— ์žˆ๊ธดํ•˜๋‹ค๋ฉด
                // ๊ฐ€์žฅ ์ž‘์€ ์ˆ˜์˜ index๋ฅผ ์ฐพ๊ธฐ
                for (int k = 0; k < keymap.length; k++) {
                    String temp = keymap[k];
                    int index = temp.indexOf(ch);
                    // index != -1์„ ๋„ฃ์–ด ์ค˜์•ผ keymap[0]์—์„œ indexOf๊ฐ’์ด 0์ด๊ณ 
                    // keymap[1]์—์„œ indexOf๊ฐ’์ด -1๋กœ ๋–จ์–ด์ง„๋‹ค๋ฉด ๋งˆ์ง€๋ง‰์— cnt๊ฐ€ ๊ณ„์† 0์œผ๋กœ ์•ˆ๋จ.
                    if (index < maxIndex && index != -1) {
                        maxIndex = index;
                    }
                }
                cnt += maxIndex + 1; // ๋ˆ„๋ฅด๋Š” ํšŸ์ˆ˜๋Š” index + 1ํšŒ
            }
            if (answer[i] != -1) {
                answer[i] = cnt;
            }
        }
        return answer;
    }
}