【问题标题】:codingBat xyzMiddle fails in other testscodingBat xyzMiddle 在其他测试中失败
【发布时间】:2015-05-20 10:14:38
【问题描述】:

这是我的任务: 给定一个字符串,“xyz”是否出现在字符串的中间?要定义中间,我们会说“xyz”左右的字符数最多相差一个。

others用例中的问题描述和失败可以通过here下面的代码看到

xyzMiddle("AAxyzBB") → 真

xyzMiddle("AxyzBB") → 真

xyzMiddle("AxyzBBB") → 假

我的解决方案如下。由于我看不到“其他测试”是什么,请帮我找出问题所在。我的方法是检查'y'是否出现在奇数或偶数字符串的中间。

public boolean xyzMiddle(String str) {
  if (str.indexOf("xyz") < 0) return false;
  int l = str.length();
  int m = l / 2;
  if (l % 2 != 0) {
   if (str.charAt(m) != 'y') return false;
  }
  else {
   if (str.charAt(m) != 'y' && str.charAt(m - 1) != 'y') return false;
  }
  return true; 
}

【问题讨论】:

    标签: java string


    【解决方案1】:

    你的解决方案的问题是你只是returning false in case the string in question has odd length

    这实际上是不正确的,the pass use-cases 这个任务可以在数学上划分如下:

    1)xyz 出现在中间,长度为x + 1 和x 的字符串在其左侧或右侧。

    以字符串xyz的长度为3,总长度为:

    (x) + 3 + (x + 1) = 2x + 4 --->总是偶数 所以在上面的例子中,我们只检查 xyz 是否在中间并相应地返回,这已经在你的代码中处理了。

    2) 中间有xyz,左边或右边有长度为x的字符串。

    再次将字符串 xyz 的长度设为 3,总长度为:

    (x) + 3 + (x) = 2x + 3 --->总是奇数

    因此,根据您在这种情况下返回true 的解决方案(最后一行代码),您需要过滤掉length is odd 但xyz 不在中间的情况,如下所示:

    if (!(str.substring((m - 1), m + 2).equals("xyz"))) 
       return false;
    

    包含此内容后,您的解决方案如下所示:

    public boolean xyzMiddle(String str) {
      if (str.indexOf("xyz") < 0) return false;
      int l = str.length();
      int m = l / 2;
      if (l % 2 != 0) {
       if (!(str.substring((m - 1), m + 2).equals("xyz"))) 
       return false;
      }
      else {
       if (str.charAt(m) != 'y' && str.charAt(m - 1) != 'y') return false;
      }
      return true; 
    }
    

    现在它通过了codingBat的所有测试。

    【讨论】:

    • 知道了!像“xyzyabc”这样的输入可能会在我的代码中给出错误的结果。谢谢。
    • 我相信它是 AAxyzBB 或 AxyzA,正如我的回答中所解释的那样,它们是奇数长度的字符串。
    【解决方案2】:
    if(str.length() <3) return false;
    
       int ind = str.indexOf("xyz", str.length()/2 - 3) ;
       String first = str.substring(0, ind);
       String second = str.substring(ind+3);
    
      return (first.length() == second.length() || first.length() +1 == second.length() || first.length() == second.length() + 1);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多