mercredi 21 décembre 2016

Why is my code returning false for the following conditions?

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

Aucun commentaire:

Enregistrer un commentaire