java - 查找重复的单词

标签 java string algorithm

我有这个任务需要做

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

Failed test

最佳答案

不需要嵌套循环。我们所要做的就是检查当前字符是否等于前一个:

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/

相关文章:

Java 通过套接字传输多个文件

java - 如何让单元测试在 java 7 : java. lang.VerifyError 中运行:在分支目标处期望堆栈映射框架

string - 为数据中的每一行构造一个标识符字符串

c++ - 初始化字符串数组中的值 C++

php - 超出执行时间

algorithm - 如何找到 PostgreSQL 存储删除算法?

java - 使用 GPS 时出现权限错误

java - 增加数组的值计数

regex - 修剪具有不同字符的字符串的前导和尾随部分

algorithm - 计算通过图形的路径数