[Java] 모음사전 - Lv2 프로그래머스 완전탐색 / 코딩테스트 고득점 Kit

P.S./프로그래머스 2023. 4. 19. 16:14
728x90
728x90

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

 

프로그래머스

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

programmers.co.kr

 

 

풀이


DFS를 이용해서 간단하게 풀어냈다.

class Solution {
	
    static int idx = 0;
    static int answer = -1;
	
    public int solution(String word) {   	
        dfs(word, "");        
        return answer;
    }
    
    public void dfs(String word, String text) {
    	if(answer > 0) return;
    	if(word.equals(text)) {
    		answer=idx;
    	}
    	idx++;
    	if(text.length()==5) {    		
    		return;
    	}
    	
    	dfs(word, text+"A");
    	dfs(word, text+"E");
    	dfs(word, text+"I");
    	dfs(word, text+"O");
    	dfs(word, text+"U");
    }

}

 

 

 

 

다른 풀이


프로그래머스에서 인상깊은 두가지 코드를 가져왔다.

 

첫번째는 모든 낱말의 개수를 per에 담아 조건에맞는 결과를 출력하는 코드인데

수학적 머리만 따라주면 간결하게 이런식으로 코드를 짤 수 있지만, 단점은 단어의 조건이 바뀔 때, per의 값이 계속 변해야 한다는 점이다.

 

class Solution {
    public int solution(String word) {
        int answer = 0, per = 3905;
        for(String s : word.split("")) answer += "AEIOU".indexOf(s) * (per /= 5) + 1;
        return answer;
    }
}

 

아래의 풀이는, 재귀를 돌리긴 하지만, 내가 나눠놓은 재귀호출을 반복문으로 한번에 처리했다.

import java.util.*;
class Solution {
    List<String> list = new ArrayList<>();
    void dfs(String str, int len) {
        if(len > 5) return;
        list.add(str);
        for(int i = 0; i < 5; i++) dfs(str + "AEIOU".charAt(i), len + 1);
    }
    public int solution(String word) {
        dfs("", 0);
        return list.indexOf(word);
    }
}

 

흡수해서 더 나은 코드를 짤수있도록 노력하자

728x90
300x250
mag1c

mag1c

2년차 주니어 개발자.

방명록