코딩테스트/프로그래머스
[프로그래머스/java] 모음사전 - 재귀를 이용하여 푸는 문제
drCode
2022. 4. 1. 00:23
728x90
반응형
https://programmers.co.kr/learn/courses/30/lessons/84512
코딩테스트 연습 - 모음사전
사전에 알파벳 모음 'A', 'E', 'I', 'O', 'U'만을 사용하여 만들 수 있는, 길이 5 이하의 모든 단어가 수록되어 있습니다. 사전에서 첫 번째 단어는 "A"이고, 그다음은 "AA"이며, 마지막 단어는 "UUUUU"입니
programmers.co.kr
재귀를 이용하여 푸는 문제입니다.
제시되는 단어의 순서를 맞추는 문제입니다.
길이가 5가 될 때까지 단어를 추가해주고
길이가 5 이하이면 함수를 재귀적으로 호출하여 넘겨받은 인덱스와 이전에 완성된 단어를 넘겨주어
원하는 단어가 나오면 리턴해주면 됩니다.
이 문제를 풀면서 했던 뻘짓은
public class VowelDictionary {
public static void main(String[] args) {
Solution s = new Solution();
System.out.println(s.solution("AAAAE"));
System.out.println(s.solution("AAAE"));
System.out.println(s.solution("I"));
System.out.println(s.solution("EIO"));
}
}
각 케이스에서 사용하는 객체를 따로따로 선언해주어야 했는데
하나의 객체로 모든 케이스를 테스트하였다.
package combination.vowelDictionary;
public class VowelDictionary {
public static void main(String[] args) {
Solution s1 = new Solution();
System.out.println(s1.solution("AAAAE"));
Solution s2 = new Solution();
System.out.println(s2.solution("AAAE"));
Solution s3 = new Solution();
System.out.println(s3.solution("I"));
Solution s4 = new Solution();
System.out.println(s4.solution("EIO"));
}
}
class Solution {
char[] arr = {'A', 'E', 'I', 'O', 'U'};
int num = 0;
String word;
boolean isFind = false;
public int solution(String word) {
this.word = word;
find(0, "");
return num;
}
public void find(int idx, String str) {
for (int i = idx; i < 5; i++) {
String temp = str + arr[i];
int len = temp.length();
num++;
if(word.equals(temp)) {
isFind = true;
return;
}
if(len == 5) continue;
find(idx, temp);
if(isFind) return;
}
}
}
728x90
반응형