public static boolean Xish
This method should take in two parameters, in the following order: A String of the word to check and a String made up of the letters to check for. For example, a word is considered elf-ish, if it contains the letters e, l, and f, in any order (“waffle”, “rainleaf”)
and a true return of the method would be Xish(“waffle”, ”elf”)
. If there are multiple occurrences of a letter to check for, it must occur multiple times in the search word. Return true if the word contains all the needed characters and false if it does not contain all the characters.
This is what I have so far, but I am lost how I would recall the method and check to see if there are multiple occurrences (2nd part).
public static boolean Xish(String check, String letters) {
String word = check;
String contains= letters;
if(word.indexOf(contains) >= 0)
return true;
else
return false;
}
Actually, doing this recursively will also take care of the multiple occurrences issue.
First, your own method is not really correct - it looks for the whole letters
in the word. That is, if letters
is elf
, then true will be returned for self
, but not for heartfelt
, and that's wrong. You are supposed to look for the individual letters, because the order is not important.
For recursion:
If the letters
is an empty string - return true. You can say that any word is fine if there are no restrictions.
If the check
is an empty string - return false. An empty string does not contain the letters in letters
(and we already know that letters is not empty).
Take the first letter in letters
. Look for it in check
. If it's not there, return false.
If it was there, then call the same method, but pass only what remains of check
and letters
. For example, if check
was selfish
and letters
was elf
, you found that e
exists. Return the result of Xish("slfish","lf")
. This will take care of the multiple occurrences. You do that by using substring
and concatenating the applicable parts.
If multiple occurrences weren't an issue, you could pass the check
as-is to the next level of the recursion. But since they matter, we need to remove one letter for each letter requested, to make sure that we don't match the same position again for the next occurrenc.