开发者

Programming exercise

开发者 https://www.devze.com 2023-03-29 05:14 出处:网络
Hi I have been doing the J开发者_开发技巧avabat exercises and I have found myself in a bit of a snag with this problem:

Hi I have been doing the J开发者_开发技巧avabat exercises and I have found myself in a bit of a snag with this problem:

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

public boolean xyBalance(String str) {

  if(str.length() < 2){

    if(str == "x"){

    return false;

    }

    return true;

  }

  for (int i = 0 ; i < str.length()- 1;i++){

  if (str.charAt(i)=='x' && str.charAt(i + 1) == 'y'){

  return true;

  }

  }

  return false;
}


  1. Find the position of the last x
  2. Find the position of the last y
  3. Return xPos < yPos.

(I'll leave special cases, such as if no x or no y are found as another exercise ;-)


Your method returns true as soon as it finds an 'x' immediately followed by a 'y' in the given string. So it will give incorrect results to your original problem in most of the cases.

I don't give you the full solution, only a hint, so that you actually learn to solve the problem yourself. Basically you need to determine whether there is a 'y' in the string after the last occurrence of 'x'. For this, use String.lastIndexOf.


Your logic is flawed: you return true (i.e. you end the loop and give a result) as soon as you find an x directly followed by an y. This is not what the program should do.

Also, if the string length is les than 2, you're comparing strings with ==. This compares the references (pointers) and not the contents of the strings. Use s1.equals(s2) to compare the contents of two strings.

Here's how I would code the algorithm (other solutions using indexOf are potentially more efficient, but they don't use a loop. If you want to keep using a loop, this solution should work).

  • Initialize a boolean variable balanced to true
  • start looping on each character of the string.
  • if the current character is an x, set balance to false.
  • if the current character is an y, reset balanced to true.
  • when the loop is finished, return the value of balanced.


public boolean xyBalance(String str) {
    if(!str.contains("x")) { return true; }
    int x = str.lastIndexOf("x");
    int y = str.lastIndexOf("y");
    return x < y;
}

From top to bottom: If there is no x in the string, it must be balanced so return true. Get the last instance of x. Get the last instance of y. If the last x is before the last y, return true, otherwise, return false.

This is the easiest and cleanest way I can think of.


Here's a way to solve this using charAt() and an iteration loop:

   public boolean xyBalance(String str) {
      //start from the end of the string
      for (int i = str.length()-1;i>=0;i--)
      {
        if (str.charAt(i) == 'x')
        {
          //starting from the index of the last 'x', check the rest of the string to see if there is a 'y'
          for (int j = i; j < str.length(); j++)
          {
            if (str.charAt(j) == 'y')
            {
              //balanced
              return true;          
            }
          }
          //no 'y' found so not balanced
          return false; 
        }     
      }
      //no 'x' found at all so we are balanced
      return true;
    }


    public boolean xyBalance(String str) {
//intialize x and y value to 0
     int x = 0;
     int y = 0;
//run a for loop and check for x value
     for (int i = 0; i < str.length(); i++) {
      if (str.charAt(i) == 'x') {
//if condition is true increment x value
       x++;
//now run a for loop for y only if x condition is true , here it will run from "i" position where we got x value
       for (int j = i; j < str.length(); j++) {
        if (str.charAt(j) == 'y') {
//once we get value which matches 'y' increment y and break from here so that it will not count more 'y'
         y++;
         break;
        }
       }
      }
     }

//after this check x and y count  
     if (x == y) {
      return true;
     } else {
      return false;
     }

    }


my solution:

public static boolean xyBalance(String str) {

      boolean xBefore = false;
      boolean yAfter = false;

      for (int i = 0; i < str.length(); i++) {
        if (str.charAt(i)=='x') {
            xBefore = true;
            yAfter = false;
        }
        if (str.charAt(i)=='y') {
            xBefore = false;    
            yAfter = true;
        }

    }
      if (yAfter || xBefore==false) {
          return true;
      }

      return false;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消