Seren dev's blog
article thumbnail

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

 

프로그래머스

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

programmers.co.kr

풀이 - 완전탐색

완전탐색으로 만들 수 있는 모든 문자열을 순서에 맞게 탐색하며 카운팅하고, 정답을 찾으면 탐색을 모두 중단한다.

코드

class Solution {
    static char[] alphabet = {'A', 'E', 'I', 'O', 'U'};
    static int cnt = 0; // 정답
    static boolean flag; // 정답을 찾았을 때 true로 변경
    
    public int solution(String word) {
        dfs(0, "", word);
        return cnt;
    }
    
    public static void dfs(int size, String seq, String word) {
        if (size == 5 || flag) return;
        
        for (int i = 0; i < 5; i++) {
            if (flag) return; // 답을 찾았으므로 탐색 종료
            
            String newStr = seq + alphabet[i];
            cnt++;
            
            if (newStr.equals(word)) { // 답을 찾았으므로 flag를 true로 변경
                flag = true;
                return;
            }
            
            dfs(size+1, newStr, word);
        }
    }
}

다른 풀이 - 규칙을 이용한 풀이

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

참고

https://arinnh.tistory.com/86

https://seongho96.tistory.com/50

 

728x90
profile

Seren dev's blog

@Seren dev

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!