Java检查字符串中的重复字母

0 java input letters-and-numbers

我在弄清楚如何检查用户输入的重复字母时遇到问题。程序需要将重复的字母输出为 true,如果没有则输出为 false。程序不应计算重复的数字或符号。

例如:

  • 用户输入:巧克力
    程序输出:True

  • 用户输入:112cream
    程序输出:False

gus*_*stf 5

这是另一个版本,基于 @rell 的回答,但没有HashSet或char[]创建。

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;
}
Run Code Online (Sandbox Code Playgroud)

对于较小的输入字符串,这很可能会更快。但对于较长的输入字符串,@rell 的版本可能更快,因为他使用的是HashSetwithO(1)查找/插入,并且由于循环O(n)总数是O(n)。我的解决方案是O(n^2)(循环O(n)乘以indexOfwith O(n)),最坏情况的输入将是这样的abcdefghijklmnopqrstuvwxyzz。

使用流更新另一个版本。

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

更新修复了流版本中的错误