我在CodingBat.com上练习Java,但遇到了问题。
zipZap(“ azbcpzpp”)返回“ azbcpzpp”。预期返回“ azbcpzp”
谢谢
// http://codingbat.com/prob/p180759
// Look for patterns like "zip" and "zap" in the string -- length-3,
// starting with 'z' and ending with 'p'. Return a string where for
// all such words, the middle letter is gone, so "zipXzap" yields "zpXzp".
public String zipZap(String str) {
if (str.length() < 2)
return str;
String result = str.substring(0, 1);
for (int i=1; i < (str.length()-1) ; i++) {
if ((str.charAt(i-i) != 'z') || (str.charAt(i+1) != 'p'))
result += str.charAt(i);
}
result += str.substring(str.length()-1);
return result;
}
将if条件更改为if ((str.charAt(i - 1) != 'z') || (str.charAt(i + 1) != 'p'))
。否则,您始终检查索引0处的char是否等于'z',因为i-i
它始终为0。
public static String zipZap(String str)
{
if (str.length() < 2)
return str;
String result = str.substring(0, 1);
for (int i = 1; i < (str.length() - 1); i++)
{
if ((str.charAt(i - 1) != 'z') || (str.charAt(i + 1) != 'p'))
result += str.charAt(i);
}
result += str.substring(str.length() - 1);
return result;
}
Input: azbcpzpp
Output: azbcpzp
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句