주녘공부일지

[프로그래머스 C#] Lv.2 모음사전 본문

Programmers - C#/CodingTest Lv.2

[프로그래머스 C#] Lv.2 모음사전

주녘 2024. 2. 9. 16:19
728x90

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

1. 정답코드 및 핵심 아이디어, 유의사항

주어진 조건에 따른 사전에서 찾는 단어가 몇번째로 있는지 찾는 문제

- 조건에 따라 알파벳으로 만들 수 있는 모든 단어를 list에 저장 ( DFS 이용 )

- 저장한 list를 오름차순 정렬하여 주어진 문제처럼 순서대로 배치

 ex) list[0] : A, list[1] : AA, list[2] : AAA ....

 

DFS 알고리즘

https://godgjwnsgur7.tistory.com/47

 

[Algorithm C#] BFS, DFS ( + Back Tracking )

1. BFS(Breadth First Search) - 너비 우선 탐색 최단 경로, 임의의 경로를 찾고 싶을 때, 등에 사용 - 큐(FIFO) 사용 // 큐를 이용 public void BFS(int index) { Node root = nodes[index]; Queue queue = new Queue(); queue.Enqueue(root

godgjwnsgur7.tistory.com

주석 참조

    using System;
    using System.Collections.Generic;

    public class Solution
    {
        public int solution(string word)
        {
            var list = new List<string>(); // 알파벳 사전 리스트
            var charArray = new Char[5] { 'A', 'E', 'I', 'O', 'U' };
            
            // 각 자릿수에 대한 모든 경우의 수를 list에 넣기
            for (int i = 1; i <= charArray.Length; i++)
                DFS("", 0, i, charArray, list);
                
            // 오름차순 정렬
            list.Sort();
            return list.FindIndex(s => s == word) + 1;
        }

        public void DFS(string str, int currLength, int maxLength, char[] charArray, List<string> list)
        {
            // 목표 자리 수에 도달
            if (currLength == maxLength)
            {
                list.Add(str);
                return;
            }
            
            for (int i = 0; i < charArray.Length; i++)
                DFS(str + charArray[i], currLength + 1, maxLength, charArray, list);
        }
    }
728x90