링크 : 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;
}
}
}
}'알고리즘 > 프로그래머스' 카테고리의 다른 글
| [프로그래머스] N개의 최소공배수(Java) (0) | 2024.10.31 |
|---|---|
| [프로그래머스] k진수에서 소수 개수 구하기 (4) | 2024.10.28 |
| [프로그래머스] 미로 탈출(Java) (3) | 2024.10.22 |
| [프로그래머스] 다리를 지나는 트럭(Java) (2) | 2024.10.21 |
| [프로그래머스] 카펫(Java) (2) | 2024.10.17 |