본문 바로가기
알고리즘/프로그래머스

[프로그래머스] 모음 사전(Java)

by hxxyeoniii 2024. 10. 26.

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

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr


문제 풀이

1. 완전탐색 알고리즘을 사용해 만들어지는 문자열을 모두 파악한다.

2. 이때 만들어지는 문자열을 list에 담아 저장한다.

3. dfs를 모두 수행한 후 list에서 찾으려는 문자열을 검색하고 index를 반환해준다.

import java.util.*;

class Solution {
    
    static String[] alph = {"A", "E", "I", "O", "U"};
    static int answer;
    static List<String> list = new ArrayList<>();
    
    public int solution(String word) {
        
        dfs("", 0);
        
        for(int i=0; i<list.size(); i++) {
            if(list.get(i).equals(word)) {
                answer = i;
                break;
            }
        }
        
        return answer;
    }
    
    static void dfs(String str, int depth) {
        list.add(str);
        
        if(depth >= 5) {
            return;
        }
        
        for(int i=0; i<alph.length; i++) {
            depth += 1;
            dfs(str + alph[i], depth); 
            depth -= 1;
        }
    }
}

 


리스트를 사용하지 않은 풀이

import java.util.*;

class Solution {
    
    static String[] alph = {"A", "E", "I", "O", "U"};
    static int answer;
    static int count;
    
    public int solution(String word) {
        
        dfs("", 0, word);
        
        return answer;
    }
    
    static void dfs(String str, int depth, String word) {
        count++;
        
        if(depth >= 5) {
            return;
        }

        for(int i=0; i<alph.length; i++) {
            if(word.equals(str + alph[i])) {
                answer = count;
                break;
            } else {
                depth += 1;
                dfs(str + alph[i], depth, word); // depth는 문자열(str)의 길이랑 동일함
                depth -= 1;
            }
        }
    }
}