Skip to content
Advertisement

Java repeated letter check in string

I’m having problem figuring out how to check from users input letters that were repeated. Program needs to output repeated letter as true and if there isn’t any then as false. Program should not count numbers or symbols as repeated.

For example:

  • User input: Chocolate
    Program Output: True

  • User input: 112 cream
    Program Output: False

Advertisement

Answer

Here is another version, based on answer from @rell but with no HashSet or char[] creation.

private static boolean check(String input) {
    for (int i = 0; i < input.length(); i++) {
        char ch = input.charAt(i);
        if (Character.isLetter(ch) && input.indexOf(ch, i + 1) != -1) {
            return true;
        }
    }
    return false;
}

For smaller input strings, this will most likely be faster because of that. But for longer input strings, the version from @rell is potentially faster as he is using a HashSet with O(1) lookup/insert, and since the loop is O(n) the total is O(n). And my solution is O(n^2) (loop O(n) multiplied with indexOfwith O(n)), worst case input would be something like this abcdefghijklmnopqrstuvwxyzz.

Update Another version with streams.

private static boolean check(String input) {
    IntStream characters = input.codePoints().filter(Character::isLetter);
    return characters
            .distinct()
            .count() == characters.count();
}

Update Fixed bug in stream version

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement