我有这个任务需要做
Write a method that takes a String parameter. If the String has a double letter (i.e. contains the same letter twice in a row) then it should return true. Otherwise, it should return false.
This method must be named hasRepeat() and have a String parameter. This method must return a boolean.
但是,当我 checkin 代码时,我未通过一些测试。
它表示,当没有重复的字母时,它不会返回 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;
}
关于java - 查找重复的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69756280/