문제 풀기/C#

66. 대충 만든 자판(Dictionary)

kagan-draca 2025. 2. 18. 14:23

 

기본 틀 :

 

using System;

public class Solution {
    public int[] solution(string[] keymap, string[] targets) {
        int[] answer = new int[] {};
        return answer;
    }
}

 

문제를 보고 처음에는 곧 바로 targets와 keymap을 이용해 반복시키면서 원하는 결과를 얻을려고 했다.

 

하지만, 그럴 경우 targets에서 target을 얻기 위한 반복문, target에서 문자를 얻기 위한 반복, keymap에서 문자열을 얻기 위한 반복, 문자열에서 문자를 얻기 위한 반복

 

총 4중 반복문 형태로 굉장히 코드가 복잡해지고 수행시간에서 안 좋게 된다.

 

그래서, 

 

keymap에서 문자를 조회하면서 문자가 나오는 가장 빠른 index를 먼저 저장해야겠다

 

생각했고 Dictionary를 통해 문자를 key, index를 value로 구현할 수 있었다.

 

이후는 간단하게 targets와 dictionary를 순회하면서 입력 가능하면 횟수, 불가능하면 -1을 출력하도록 만들어줬다.

using System;
using System.Collections.Generic;

public class Solution {
    public int[] solution(string[] keymap, string[] targets) 
    {
        int[] result = new int[targets.Length];
        Dictionary<char, int> dict = new Dictionary<char,int>();
        
        foreach(string row in keymap)
        {
            for(int i = 0; i < row.Length; i++)
            {
                dict[row[i]] = dict.ContainsKey(row[i]) ? Math.Min(dict[row[i]], i + 1) : i + 1;
            }
        }
        
        for(int i = 0; i < targets.Length; i++)
        {
            string target = targets[i];
            int count = 0;
            for(int j = 0; j < target.Length; j++)
            {
                if(dict.ContainsKey(target[j])) count += dict[target[j]];
                else 
                {
                    count = -1;
                    break;
                }
            }
            result[i] = count;
        }
        
        return result;
    }
}

'문제 풀기 > C#' 카테고리의 다른 글

68. 햄버거 만들기 (SequenceEqual)  (0) 2025.02.19
67. 둘만의 암호  (0) 2025.02.18
65. 문자열 나누기  (0) 2025.02.12
64. 체육복  (0) 2025.02.12
63. 숫자 짝수 (Dictionary)  (0) 2025.02.11