Find repeated words

Viewed 594

I have this assignment where need to

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.

However, when I check in my code, I am failing some tests.

It says that it isn't returning false when there are no repeated letters.

Here is my code:

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

2 Answers

There's no need in nested loops. All we have to do is to check if current char equals to 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;
}
Related