대충 만든 자판
https://school.programmers.co.kr/learn/courses/30/lessons/160586
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
처음에 고민이 되었던 게 tapCountArr라는 배열을 만들고 나서 0이라는 초기값과 값 중에서 어떻게 최소값을 가져올지가 문제였다.
이후에 int.MaxValue 프로퍼티를 일치하지 않는 값에 넣어준 뒤 최소값을 뽑아내는 방식으로 해결했다.
using System;
using System.Linq;
public class Solution {
public int[] solution(string[] keymap, string[] targets) {
int[] answer = new int[targets.Length];
int[] tapCountArr = new int[keymap.Length];
for (int i = 0; i < targets.Length; i++)
{
for (int j = 0; j < targets[i].Length; j++)
{
for(int k = 0; k < keymap.Length; k++)
{
int index = Array.IndexOf(keymap[k].ToCharArray(), targets[i][j]);
if (index != -1)
{
tapCountArr[k] = index + 1;
}
else
{
tapCountArr[k] = int.MaxValue;
}
}
int min = tapCountArr.Min();
if (min == int.MaxValue)
{
answer[i] = -1;
break;
}
else
{
answer[i] += min;
}
}
}
return answer;
}
}
다른 사람의 풀이
딕셔너리로 최소값이면 value 값에 넣어주는 방식도 좋은 것 같다.
using System;
using System.Collections.Generic;
public class Solution {
public int[] solution(string[] keymap, string[] targets)
{
// dictionary에 최소값으로 넣어줌
var dict = new Dictionary<char, int>();
for(int i = 0; i < keymap.Length; i++)
{
string keyStr = keymap[i];
for(int k = 0; k < keyStr.Length; k++)
{
char c = keyStr[k];
dict[c] = dict.ContainsKey(c) ? Math.Min(k, dict[c]) : k;
}
}
// dictionary에서 검색 후 출력
int[] answer = new int[targets.Length];
for(int i = 0; i < targets.Length; i++)
{
string targetStr = targets[i];
for(int k = 0; k < targetStr.Length; k++)
{
if(!dict.TryGetValue(targetStr[k], out int index))
{
answer[i] = -1;
break;
}
answer[i] += index + 1;
}
}
return answer;
}
}
'알고리즘' 카테고리의 다른 글
프로그래머스 - 체육복 (0) | 2023.09.06 |
---|---|
프로그래머스 - 옹알이 (2) (0) | 2023.09.06 |
프로그래머스 - 숫자 짝궁 (0) | 2023.09.06 |
프로그래머스 - 로또의 최고 순위와 최저 순위 (0) | 2023.09.06 |
프로그래머스 - 시저 암호 (0) | 2023.08.30 |