Contents

Vowel dictionary (with.Java)

   Aug 12, 2024     2 min read

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

wordresult
β€œ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.