Manas Bajaj Manas Bajaj - 4 months ago 35
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 "x.xyz" does not.


xyzThere("abcxyz") → true
xyzThere("abc.xyz") → false
xyzThere("xyz.abc") → 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:

xyzThere("abc.xyzxyz")


How can I make it pass all tests?

Answer
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"));
}
Comments