这是我的任务: 给定一个字符串,“xyz”是否出现在字符串的中间?为了定义中间,我们可以说“xyz”左侧和右侧的字符数必须至少相差一个。
使用下面的代码here可以看到问题描述和others
用例中的失败
xyzMiddle(“AAxyzBB”)→true
xyzMiddle(“AxyzBB”)→true
xyzMiddle(“AxyzBBB”)→false
我的解决方案如下。由于我无法看到“其他测试”是什么,请帮我发现问题。我的方法是检查'y'是否出现在奇数或偶数字符串的中间。
public boolean xyzMiddle(String str) {
if (str.indexOf("xyz") < 0) return false;
int l = str.length();
int m = l / 2;
if (l % 2 != 0) {
if (str.charAt(m) != 'y') return false;
}
else {
if (str.charAt(m) != 'y' && str.charAt(m - 1) != 'y') return false;
}
return true;
}
答案 0 :(得分:0)
您的解决方案的问题在于您只是returning false in case the string in question has
奇数 length
实际上并非如此,此任务的the pass use-cases
可以在数学上划分如下:
1)中间有
xyz
,其左侧或右侧有一个长度为x + 1
和x
的字符串。
将字符串xyz
的长度设为3,总长度为:
(x) + 3 + (x + 1)
= 2x + 4
---&gt; 始终均匀
所以在上面的情况下,我们只检查xyz
是否在中间,并相应地返回,这已经在你的代码中处理过了。
2)中间有
xyz
,左侧或右侧有长度为x
的字符串。
再次将字符串xyz
的长度设为3,总长度为:
(x) + 3 + (x)
= 2x + 3
---&gt; 总是奇怪
因此,根据您在这种情况下返回true
的解决方案(最后一行代码),您需要在length is odd
但xyz
不在中间的情况下过滤掉案例,如下所示:
if (!(str.substring((m - 1), m + 2).equals("xyz")))
return false;
包含此功能,您的解决方案如下所示:
public boolean xyzMiddle(String str) {
if (str.indexOf("xyz") < 0) return false;
int l = str.length();
int m = l / 2;
if (l % 2 != 0) {
if (!(str.substring((m - 1), m + 2).equals("xyz")))
return false;
}
else {
if (str.charAt(m) != 'y' && str.charAt(m - 1) != 'y') return false;
}
return true;
}
现在它通过了codingBat上的所有测试。
答案 1 :(得分:0)
if(str.length() <3) return false;
int ind = str.indexOf("xyz", str.length()/2 - 3) ;
String first = str.substring(0, ind);
String second = str.substring(ind+3);
return (first.length() == second.length() || first.length() +1 == second.length() || first.length() == second.length() + 1);