Manas Bajaj Manas Bajaj - 1 year ago 116
Java Question

Return true if string cointains "xyz" not preceeded by a period?

I'm trying to solve this CodingBat problem:

Return true if the given string contains an appearance of "xyz" where the xyz is not directly preceeded by a period (.). So "xxyz" counts but "" does not.

xyzThere("abcxyz") → true
xyzThere("") → false
xyzThere("") → true

My attempt:

public boolean xyzThere(String str) {
boolean res = false;

if(str.contains(".xyz") == false && str.contains("xyz")){
res = true;

return res;


The problem is that is passes all the tests except the one below because it contains two instances of xyz:


How can I make it pass all tests?

Answer Source
public boolean xyzThere(String str) {
    return(!str.contains(".xyz") && str.contains("xyz"));

Edit: Given that ".xyzxyz" should return true, the solution should be:

public boolean xyzThere(String str) {
    int index = str.indexOf(".xyz");
    if(index >= 0) {
        return xyzThere(str.substring(0, index)) || xyzThere(str.substring(index + 4));
    } else return (str.contains("xyz"));