0

我正在学习 Java CodeBat 练习。这是我坚持的一个

在字符串中查找诸如“zip”和“zap”之类的模式——长度为 3,以 'z' 开头并以 'p' 结尾。返回一个字符串,其中对于所有此类单词,中间字母都消失了,因此“zipXzap”产生“zpXzp”。

这是我的代码:

    public String zipZap(String str){

    String s = ""; //Initialising return string
    String diff = " " + str + " "; //Ensuring no out of bounds exceptions occur

    for (int i = 1; i < diff.length()-1; i++) {
        if (diff.charAt(i-1) != 'z' &&
                diff.charAt(i+1) != 'p') {
            s += diff.charAt(i);
        }
    }
    return s;
}

这对他们中的一些人来说是成功的,但对其他人来说却不是。对于某些示例字符串,该&&运算符似乎表现得像 a ;||也就是说,很多我想保留的角色都没有保留。我不确定我将如何修复它。

如果您愿意,请朝正确的方向轻推!我只需要一个提示!

4

3 回答 3

2

事实上,情况恰恰相反。你应该做:

if (diff.charAt(i-1) != 'z' || diff.charAt(i+1) != 'p') {
    s += diff.charAt(i);
}

这相当于:

if (!(diff.charAt(i-1) == 'z' && diff.charAt(i+1) == 'p')) {
    s += diff.charAt(i);
}
于 2015-04-07T17:12:08.237 回答
1

这听起来像是对正则表达式的完美使用。

正则表达式"z.p"将匹配任何以 az 开头、中间有任何字符并以 p 结尾的三个字母标记。如果您要求它是一个字母,您可以使用它"z[a-zA-Z]p"

所以你最终得到

public String zipZap(String str) {
    return str.replaceAll("z[a-zA-Z]p", "zp");
}

顺便说一句,这通过了所有测试。

你可以说这个问题是关于原始字符串操作的,但我认为这会成为一个更好的教训:适当地应用正则表达式是一项非常有用的技能!

于 2015-04-07T17:14:38.800 回答
0
public String zipZap(String str) {
    //If bigger than 3, because obviously without 3 variables we just return the string.
    if (str.length() >= 3)
    {
      //Create a variable to return at the end.
      String ret = "";
      //This is a cheat I worked on to get the ending to work easier.
      //I noticed that it wouldn't add at the end, so I fixed it using this cheat.
      int minusAmt = 2;
      //The minus amount starts with 2, but can be changed to 0 when there is no instance of z-p.
      for (int i = 0; i < str.length() - minusAmt; i++)
      {
        //I thought this was a genius solution, so I suprised myself.
        if (str.charAt(i) == 'z' && str.charAt(i+2) == 'p')
        {
          //Add "zp" to the return string
          ret = ret + "zp";
          //As long as z-p occurs, we keep the minus amount at 2.
          minusAmt = 2;
          //Increment to skip over z-p.
          i += 2;
        }
        //If it isn't z-p, we do this.
        else
        {
          //Add the character
          ret = ret + str.charAt(i);
          //Make the minus amount 0, so that we can get the rest of the chars.
          minusAmt = 0;
        }
      }
      //return the string.
      return ret;
    }
    //If it was less than 3 chars, we return the string.
    else
    {
      return str;
    }
  }
于 2016-12-15T05:04:27.797 回答