java - 给定一个字符串, "xyz"是否出现在字符串的中间?

标签 java

Given a string, does "xyz" appear in the middle of the string? To define middle, we'll say that the number of chars to the left and right of the "xyz" must differ by at most one. This problem is harder than it looks.

我的解决方案没有倒数第二行,除了一个条件:if str="xyx" 是否可以修改 for 循环以考虑到这一点……我正在努力理解为什么不这样做。

我的解决方案确实有效 我只是想更好地了解我在做什么。我知道我可以将它添加到第一个 if 语句中,但我想知道为什么没有它它就不能工作。

public boolean xyzMiddle(String str) {
  for (int i=0;i<str.length()-3;i++) {
    if (str.substring(i,i+3).equals("xyz")) {
      String front =str.substring(0,i);
      String end = str.substring(i+3);
      int a =Math.abs(front.length() -end.length());
      if (a<=1) return true;
    }    
  }
  if (str.equals("xyz")) return true;
  return false;

最佳答案

我想我记得这个问题 - 我相信是 this question from Codingbat 。优秀的网站,当我开始编程时从那个网站学到了很多东西。不过,绝对没有理由使用循环。

public boolean xyzMiddle(String str) {
  boolean result = false; 
  int i = str.length()/2 -1;

  if (str.length() >= 3 && (str.substring(i, i+3).equals("xyz") || (str.length()%2 == 0 && str.substring(i-1, i+2).equals("xyz"))  )) {
      result = true;
  }
  return result;
}

那么,让我们来了解一下它及其工作原理。首先,str.length() >= 3,因为如果字符串不至少与“xyz”一样长,则它不可能包含“xyz”。

这个问题有两种主要情况,我们需要考虑。弦的长度可以是均匀的,也可以是不均匀的。在不均匀的情况下,这很容易:

不平衡案例

AAAxyzAAA // length = 9
012345678 // the indexes
    ^     // that's the middle, which can be calculated by length/2
          // (since this is an integer divison, we disregard whatever comes after the decimal point)

因此,为了得到 xyz-子字符串的开始,我们只需从这个数字中减去一个 - 这正是 i 正在做的:

AAAxyzAAA // length = 9
012345678 // the indexes
   i      // i = length/2-1 = 3

所以如果 str.substring(i, i+3)xyz,我们可以返回 true!

偶数情况 现在,这可能有点棘手,因为字符串没有真正的“中间”。事实上,两个索引可以称为中间,所以我们有两个子情况:

AAAAAAAA // length = 8
01234567 // the indexes
   ^^    // Which one is the true middle character?

事实上,中间会在索引 3 和 4 之间。但是,我们正在执行整数除法,length/2 始终是两个可能的“中间”中最大的(最右边的)。由于我们使用中间部分计算 i,因此与不均匀情况相同 - str.substring(i, i+3) 可以被视为中间部分字符串。

AAAxyzAA 
01234567 
   ^^^     // str.substring(i, i+3)
   i

但假设我们的字符串是 AAxyzAAA - 可以将其视为字符串的中间部分。所以我们需要将我们的子字符串检查“向左”移动 - 所以我们从中减去 1。

AAxyzAAA 
01234567 
  ^^^      // str.substring(i-1, i+2)
   i       // i is still at "the old" location

那么它是否均匀?

要检查字符串是偶数还是非偶数,我们使用模数 运算符%。想到它的作用的最简单方法是“我除以这个数字后会剩下什么?”。所以 3 % 2 将是 1。在我们的例子中,我们要确保该数字可以被 2 整除并且没有任何剩余 - 因为这意味着它是一个偶数。因此,在进行“向左移动”检查之前,我们需要检查是否 str.length() % 2 == 0。否则,我们可能会冒险越界。如果字符串的长度为 3 个字符,我们向左移动了一个...我们将检查从索引 -1 开始的子字符串,这没有多大意义。

把它们放在一起,就可以了!

关于java - 给定一个字符串, "xyz"是否出现在字符串的中间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20402570/

相关文章:

java - 如何学习用 Java 编写操作系统程序?

java - Selenium -Java : How to get absolute path to the file

java - 无法排除小于当前日期的日期

java - java的cron库

java - 如何将.war部署到heroku

java - 防止 CloudFoundry 在 OOM(内存不足)时终止应用程序

java - JPA 实体,识别业务键

java - @context httpServletRequest 对 jersey 中 post 方法的请求为空

java - 在 Ubuntu 16 上为所有用户安装 OpenJDK 9

java - 防止 GridBagLayout 调整列大小