Answer and Explanation:
// code
class Main {
public static void main(String[] args) {
/*
*
*
* your code
*
*/
System.out.println(inDogish("aplderogad"));
System.out.println(inXish("aplderogad", "dog"));
}
// returns true if the word is in dog-ish
// returns false if word is not in dog-ish
public static boolean inDogish(String word) {
// first find d
if (dogishHelper(word, 'd')) {
// first find string after d
String temp = word.substring(word.indexOf("d"));
// find o
if (dogishHelper(temp, 'o')) {
// find string after o
temp = temp.substring(temp.indexOf("o"));
// find g
if (dogishHelper(temp, 'g'))
return true;
}
The output is attached below
}
return false;
}
// necessary to implement inDogish recursively
public static boolean dogishHelper(String word, char letter) {
// end of string
if (word.length() == 0)
return false;
// letter found
if (word.charAt(0) == letter)
return true;
// search in next index
return dogishHelper(word.substring(1), letter);
}
// a generalized version of the inDogish method
public static boolean inXish(String word, String x) {
if (x.length() == 0)
return true;
if (word.length() == 0)
return false;
if (word.charAt(0) == x.charAt(0))
return inXish(word.substring(1), x.substring(1));
return inXish(word.substring(1), x.substring(0));
}
}
PS E:\fixer> java Main true true ne on
PS E:\fixer> java Main true true ne on