Why is my code returning false for the following conditions?

188 Views Asked by At

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 =]

2

There are 2 best solutions below

2
On BEST ANSWER

The loop is never entered, if the passed String is empty, thus the method automatically returns false. The loop starts with i = 0, tries to match the condition i < str.length() - 1, where str.length() - 1 evaluates to -1, since the String 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

A String is balanced, if no 'x' occurs after the last 'y' in the String

Which makes the whole problem a lot simpler:

public boolean xyBalanced(String s){
    return s.lastIndexOf('x') <= s.lastIndexOf('y');
}
0
On

The reason you're getting the wrong result for the string "y" is that the condition in the for-loop is to run until i < str.length() -1, a fix would be changing the condition to run until: i < str.length() so you won't miss the last character.

As for running the code on empty string, since the length of the string is zero it will not get into the for-loop at all and hence will return false - so that's actually a good result!