【问题标题】:Find repeated words查找重复的单词
【发布时间】:2021-12-13 18:50:36
【问题描述】:

我有这个任务需要去

编写一个接受字符串参数的方法。如果字符串有一个双字母(即连续两次包含相同的字母),那么它应该返回 true。否则,它应该返回 false。

此方法必须命名为 hasRepeat() 并具有 String 参数。此方法必须返回一个布尔值。

但是,当我签入我的代码时,我没有通过一些测试。

它说当没有重复的字母时它不会返回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;
}

【问题讨论】:

  • 这是因为j总是以i+1开头,所以你检查相同的子串是否相等。

标签: java string algorithm


【解决方案1】:

嵌套循环不需要。我们所要做的就是检查 current char 是否等于 previous

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;
}

【讨论】:

    猜你喜欢
    • 2012-08-09
    • 1970-01-01
    • 2021-06-30
    • 2012-12-14
    • 2021-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-11
    相关资源
    最近更新 更多