我正在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;
}发布于 2015-08-31 09:45:27
将if条件更改为if ((str.charAt(i - 1) != 'z') || (str.charAt(i + 1) != 'p'))。否则,您总是检查索引0处的字符是否等于'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发布于 2020-03-09 13:22:15
public String zipZap(String str) {
String temp="";
if(str.length()<=2){
return str;
}
for(int i=0;i<str.length();i++){
if(str.charAt(i)=='z' && str.charAt(i+2)=='p'){
temp=temp+str.charAt(i);
temp=temp+str.charAt(i+2);
i=i+2;
}
else {
temp=temp+str.charAt(i);
}
}
return temp;
}发布于 2019-10-06 10:04:56
public String zipZap(String str)
{
String res="";
if (str.length()<3) return str;
for (int i=0;i<str.length()-2;i++) {
if (str.charAt(i)=='z' && str.charAt(i+2)=='p'){
res = res + str.charAt(i)+str.charAt(i+2);
i+=2;
}
else
res = res + str.charAt(i);
}
if (str.charAt(str.length()-3)!='z')
res = res + str.substring(str.length()-2);
return res;
}https://stackoverflow.com/questions/32308202
复制相似问题