Home > Back-end >  How can I count how many target words can be made from the alphabet of a given string in Java?
How can I count how many target words can be made from the alphabet of a given string in Java?

Time:03-04

There is a string s and an array of names l.

I want to count how many names of the given array with the characters of the string S can be created.

For example)

String s = "LILLYBILLYBOO";
String[] l = {"BILL", "MARIA", "LILLY"};

Through the alphabet of String s can make BILL twice, MARIA zero, LILLY once.

So the expected return value is {2,0,1}.

Is there any way to solve this problem with StringUtils or other methods other than splitting to all chars?

CodePudding user response:

Reasonably simple approach (without doing the coding for you):

  • Calculate a Map<Character, Long> from your alphabet, in your case:
{
    'L': 5,
    'I': 2,
    'Y': 2,
    'B': 2,
    'O': 2
}
  • For each word in your array, calculate the same type of Map.
  • Check each keys in each array word's Map and track the minimum value. If any character in the array words isn't in your alphabet's Map, then the answer is 0. Otherwise it is the minimum value found across all Characters. With some caution taking for dividing by the number in your array words' Map (to handle the two L's in BILL for example).
  • Related