简体   繁体   English

编程练习

[英]Programming exercise

Hi I have been doing the Javabat exercises and I have found myself in a bit of a snag with this problem:嗨,我一直在做 Javabat 练习,但我发现自己遇到了这个问题:

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.如果对于字符串中的所有 'x' 字符,在字符串的后面某处存在一个 'y' 字符,我们会说一个字符串是 xy 平衡的。 So "xxy" is balanced, but "xyx" is not.所以“xxy”是平衡的,但“xyx”不是。 One 'y' can balance multiple 'x's.一个“y”可以平衡多个“x”。 Return true if the given string is xy-balanced.如果给定的字符串是 xy 平衡的,则返回 true。

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找到最后一个x的 position
  2. Find the position of the last y找到最后y的position
  3. Return xPos < yPos .返回xPos < yPos

(I'll leave special cases, such as if no x or no y are found as another exercise;-) (我会留下特殊情况,例如如果没有找到x或没有y作为另一个练习;-)

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.从上到下:如果字符串中没有x,则必须平衡所以返回true。 Get the last instance of x.获取 x 的最后一个实例。 Get the last instance of y.获取 y 的最后一个实例。 If the last x is before the last y, return true, otherwise, return false.如果最后一个 x 在最后一个 y 之前,则返回 true,否则返回 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:这是一种使用 charAt() 和迭代循环来解决此问题的方法:

   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;
    }

Your method returns true as soon as it finds an 'x' immediately followed by a 'y' in the given string.一旦在给定的字符串中找到一个'x'后跟一个'y' ,您的方法就会立即返回 true。 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' .基本上,您需要确定在最后一次出现'x'之后字符串中是否有'y' ' 。 For this, use String.lastIndexOf .为此,请使用String.lastIndexOf

Your logic is flawed: you return true (ie you end the loop and give a result) as soon as you find an x directly followed by an y.你的逻辑是有缺陷的:只要你找到一个 x 后跟一个 y,你就会返回 true(即结束循环并给出结果)。 This is not what the program should do.这不是程序应该做的。

Also, if the string length is les than 2, you're comparing strings with ==.此外,如果字符串长度小于 2,则您将字符串与 == 进行比较。 This compares the references (pointers) and not the contents of the strings.这将比较引用(指针)而不是字符串的内容。 Use s1.equals(s2) to compare the contents of two strings.使用 s1.equals(s2) 比较两个字符串的内容。

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).这是我将如何编写算法(使用 indexOf 的其他解决方案可能更有效,但它们不使用循环。如果您想继续使用循环,这个解决方案应该可以工作)。

  • Initialize a boolean variable balanced to true初始化一个 boolean 变量balanced为真
  • start looping on each character of the string.开始循环字符串的每个字符。
  • if the current character is an x, set balance to false.如果当前字符是 x,则将 balance 设置为 false。
  • if the current character is an y, reset balanced to true.如果当前字符是 y,则将 balance 重置为 true。
  • when the loop is finished, return the value of balanced.当循环结束时,返回balanced的值。
    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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM