加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 给定一个字符串,“xyz”是否出现在字符串的中间?

发布时间:2020-12-15 05:02:23 所属栏目: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. 我的解决方案在没有

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-substring的开头,我们只需从这个数字中减去一个 – 这正是我正在做的事情:

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之间.但是,我们执行整数除法,长度/ 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开始的子字符串,这没有多大意义.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读