[英]Find repeated words
我有这个任务需要
编写一个采用 String 参数的方法。 如果 String 有一个双字母(即连续两次包含相同的字母),那么它应该返回 true。 否则,它应该返回 false。
此方法必须命名为 hasRepeat() 并具有一个 String 参数。 此方法必须返回 boolean。
但是,当我签入我的代码时,我没有通过一些测试。
它说当没有重复的字母时它不会返回false
。
这是我的代码:
public static boolean hasRepeat(String word) {
for (int i = 0; i < word.length(); i++) {
for (int j = i + 1; j < word.length(); j++) {
if (word.substring(i, i + 1).equals(word.substring(i, j))) {
return true;
}
}
}
return false;
}
不需要嵌套循环。 我们所要做的就是检查当前字符是否等于前一个:
public static boolean hasRepeat(String word)
{
// hasRepeat is a public method; we shoud be ready for any input
if (word == null)
return false;
// here we start from 1: there's no previous char for charAt(0)
for (int i = 1; i < word.length(); ++i)
if (word.charAt(i - 1) == word.charAt(i))
return true;
return false;
}
问题是当检查字符串时,循环会跳过最后两个字符串,我们可以通过将字符串的长度加 1 来解决这个问题。这是代码。 我们的代码之间的不同之处还在于 substring
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.