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

Jer*_*phy 3 java

给定一个字符串,"xyz"是否出现在字符串的中间?为了定义中间,我们将说"xyz"左侧和右侧的字符数必须至少相差一个.这个问题比它看起来更难.

我的解决方案在没有第二个最后一行的情况下工作,除了一个条件:如果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;
Run Code Online (Sandbox Code Playgroud)

Tob*_*and 9

我想我记得这个问题 - 我相信这是来自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;
}
Run Code Online (Sandbox Code Playgroud)

那么,让我们来看看这个以及它为何起作用.首先,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)
Run Code Online (Sandbox Code Playgroud)

因此,为了获得xyz-substring的开头,我们只需从这个数字中减去一个 - 这正是i在做什么:

AAAxyzAAA // length = 9
012345678 // the indexes
   i      // i = length/2-1 = 3
Run Code Online (Sandbox Code Playgroud)

如果str.substring(i, i+3)是的话xyz,我们可以回归真实!

Even Case 现在,这可能有点棘手,因为字符串没有真正的"中间".实际上,两个索引可以称为中间,因此我们有两个子案例:

AAAAAAAA // length = 8
01234567 // the indexes
   ^^    // Which one is the true middle character?
Run Code Online (Sandbox Code Playgroud)

实际上,中间位于索引3和4之间.但是,我们执行整数除法,长度/ 2始终是两个可能的"中间"中最大的(最右边).而且由于我们i使用中间值计算,与不均匀情况相同 - str.substring(i, i+3)可以认为是字符串的中间部分.

AAAxyzAA 
01234567 
   ^^^     // str.substring(i, i+3)
   i
Run Code Online (Sandbox Code Playgroud)

但是,假设我们的字符串是AAxyzAAA-这可能被认为是字符串的中间部分.所以我们需要将子字符串检查"向左移动" - 所以我们从中减去1.

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

它是偶数还是不是?

要检查字符串是偶数还是不均匀,我们使用运算符%.想到它的作用的最简单方法是"在用这个数字划分后会留下什么?".所以3 % 2将是1.在我们的情况下,我们希望确保数字可以被2整除而没有遗留任何东西 - 因为这意味着它是偶数.因此,str.length() % 2 == 0在进行"向左移动" 检查之前,我们需要检查一下.如果没有,我们可能冒险超出字符串的界限.如果字符串是3个字符长,我们向左移动一个...我们将检查从索引-1开始的子字符串,这没有多大意义.

把它们放在一起,然后你去!