I am doing Codingbat.com exercises. I am having a problem with this exercise: We'll say that a String is xy-balanced if for all the 'x' chars in the string, there exists a 'y' char somewhere later in the string. So "xxy" is balanced, but "xyx" is not. One 'y' can balance multiple 'x's. Return true if the given string is xy-balanced.
xyBalance("aaxbby") → true
xyBalance("aaxbb") → false
xyBalance("yaaxbb") → false
i know the correct solution but i was curious as to why the following solution is not working:
public boolean xyBalance(String str) {
for(int i = 0; i < str.length() -1 ;i++) {
if(str.indexOf("x") == -1 ) {
return true;
}
else if(str.charAt(str.length()-1) == 'x') {
return false;
}
else if (str.indexOf("x",i) < str.indexOf("y",i)) {
return true;
}
}
return false;
}
this code is working for all but two of the example cases:
xyBalance("y") → true **my code returns false**
xyBalance("") → true **my code returns false**
can someone explain why? thanks you =]
The loop is never entered, if the passed
String
is empty, thus the method automatically returnsfalse
. The loop starts withi = 0
, tries to match the conditioni < str.length() - 1
, wherestr.length() - 1
evaluates to -1, since theString
is empty and automatically aborts.In either way, this code wastes quite a bit of computational power. There's an a lot simpler solution available:
The problem can be translated to
Which makes the whole problem a lot simpler: