백준, 프로그래머스

[프로그래머스] 대충 만든 자판 C#

퐁스팡스 2024. 5. 16. 22:48

문제 설명

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

 

 

반복문의 반복문의 반복문 형태로 작성이 되었네요 ^^

문자열을 만들 수 없는 경우의 예외처리를 제외하고는, 단순한 구현으로 풀었습니다.

 

🎃나의 풀이

public static int[] Solution(string[] keymap, string[] targets)
{
    List<int> pressCountList = new List<int>();
    foreach (var target in targets)
    {
        int pressCount = 0;

        // targets요소의 문자 길이만큼 반복문 돌기
        for (int i = 0; i < target.Length; i++)
        {
            // 만들 수 있는 문자열인지 확인하는 불값
            bool isContain = false;

            // keymap의 원소의 최대길이 = 100
            int minIndex = 100;

            for (int j = 0; j < keymap.Length; j++)
            {
                int targetIndex = keymap[j].IndexOf(target[i]);

                // 타겟 char가 indexOf 함수를 돌렸을 때 존재 하지 않는 경우는 -1을 반환함
                if (targetIndex == -1)
                {
                    continue;
                }

                if (minIndex > targetIndex)
                {
                    minIndex = targetIndex;
                    isContain = true;
                }
            }

            // 해당 char를 만들 수 없는 경우 반복문을 종료하고 -1을 리턴
            if (isContain == false)
            {
                pressCount = -1;
                break;
            }

            pressCount += (minIndex + 1);
        }

        pressCountList.Add(pressCount);
    }

    return pressCountList.ToArray();
}