Vowel dictionary (with.Java)
This is an article about the vowel dictionary (with.Java) problem.
I would like to solve the coding test problem and reflect on the problem I solved.
Letβs get to the problem first.
Problem
The dictionary contains all words less than 5 in length that can be made using only the alphabetic vowels βAβ, βEβ, βIβ, βOβ, and βUβ.
In the dictionary, the first word is βAβ, then βAAβ, and the last word is βUUUUUUβ.
When a word is given as a parameter, complete the solution function so that it returns the number of words in the dictionary.
Restrictions
- The length of the word is 1 or more and 5 or less.
- The word only consists of the uppercase letters βAβ, βEβ, βIβ, βOβ, and βUβ.
Input/Output Examples
word | result |
---|---|
βAAAAEβ | 6 |
βAAAEβ | 10 |
βIβ | 1563 |
βEIOβ | 1189 |
my solution to the problem
import java.util.ArrayList;
class Solution {
static ArrayList<String> list;
static String[] words = {"A", "E", "I", "O", "U"};
public int solution(String word) {
int answer = 0;
list = new ArrayList<>();
dfs("", 0);
int size = list.size();
for (int i = 0; i < size; i++) {
if (list.get(i).equals(word)) {
answer = i;
break;
}
}
return answer;
}
static void dfs(String str, int len) {
list.add(str);
if (len == 5) return;
for (int i = 0; i < 5; i++) {
dfs(str + words[i], len + 1);
}
}
}
Solution Description
- word: the string you want to find
- answer: a variable that stores the result
- After generating all combinations of words, see how many times the given string comes out and return it.
- Generating words with DFS navigation
- Generates all combinations of words through the dfs method.
- Add each vowel to the current string str to generate the next level of string.
- Create all combinations through the DFS navigation and store them in the list.
- Check the number of times the given string comes out
- Check all the generated combinations and return the index if it matches the given string.
Conclusion
In this way, the code generates all combinations of words made up of a given collection through DFS navigation, and finds the number of times the given string comes out.