Java重复字母检查字符串 [英] Java repeated letter check in string
问题描述
我在弄清楚如何检查用户输入的重复字母时遇到问题.程序需要输出重复的字母为true,如果没有,则输出为false.程序不应重复计算数字或符号.
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.
例如:
-
用户输入:Chocolate
程序输出:True
User input: Chocolate
Program Output: True
用户输入:112 cream
程序输出:False
User input: 112 cream
Program Output: False
推荐答案
这里是另一个版本,基于@rell的回答,但没有 HashSet
或 char []
创造.
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;
}
对于较小的输入字符串,因此,这很可能会更快.但是对于更长的输入字符串,@ rell的版本可能会更快,因为他正在将 HashSet
与 O(1)
查找/插入一起使用,并且由于循环是 O(n)
总计为 O(n)
.我的解决方案是 O(n ^ 2)
(循环 O(n)
乘以 indexOf
和 O(n)
),最坏的情况是输入类似 abcdefghijklmnopqrstuvwxyzz
.
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 indexOf
with 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
这篇关于Java重复字母检查字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!