将给定字符串中的唯一字母添加到列表中

11

我想将一个字符串的字母添加到列表中,但只希望每个字母只添加一次。例如,如果字符串是“HELLO AM CHRISTOS WHITE”,有些字母出现了多次,因此我只希望它们被添加一次。

我考虑使用两个for循环:

for (int i=0; i< str.length(); i++){
    for(int j=0; j< str.length(); j++){
        if (str.charAt(i) != str.charAt(j)) {
            myList.add(charAt(i));
        }
    }
}

但是这段代码没有避免重复。


为什么要两个循环?可以通过单个的originalLine.toCharArray()迭代,如果(!listContains(Char.valueOf(char[i])))则添加字符(addChar())。 - Stultuske
3
你可以使用Set来实现内容的唯一性。 - Konstantin Yovkov
5个回答

14

使用 LinkedHashSet 能更高效地确定唯一字符。如果使用 LinkedHashSet,输入字符串的唯一字符顺序将得到保留。

经过一次线性时间的循环后,您可以将所有唯一字符添加到输出的 List 中。

Set<Character> unique = new LinkedHashSet<>();
for (int i = 0; i < str.length(); i++){
    unique.add(str.charAt(i));
}
myList.addAll(unique);

13
为了避免集合中出现重复元素,您不需要使用 List,而需要使用 Set(例如 HashSet)。
如果您想保留添加 String 的顺序,请使用 LinkedHashSet
最后,如果您希望您的 Set 自然排序您的 String(或能够使用 Comparator 对其进行排序),请使用 TreeSet示例
String foo = "ghghababcdef";
Set<String> hash = new HashSet<>();
Set<String> linked = new LinkedHashSet<>();
Set<String> tree = new TreeSet<>();
// iterating characters
for (char c: foo.toCharArray()) {
    // adding String representation of character to each set
    hash.add(Character.toString(c));
    linked.add(Character.toString(c));
    tree.add(Character.toString(c));
}
// printing...
System.out.println(hash);
System.out.println(linked);
System.out.println(tree);

输出

[a, b, c, d, e, f, g, h] // this may vary
[g, h, a, b, c, d, e, f] // keeps insertion order
[a, b, c, d, e, f, g, h] // sorted lexicographically by default

4

如果你想坚持使用List的解决方案,作为Set的替代选择。

你只需要循环一次,并利用List.contains(Object)方法来检查当前的char是否已经存在于你的List中。

String str = "HELLO AM CHRISTOS WHITE";
List<Character> myList = new ArrayList<>();
for(int i=0; i< str.length(); i++){
    if (!myList.contains(str.charAt(i))) {
        myList.add(str.charAt(i));
    }
}
for(char c : myList) {
    System.out.println(c);
}

输出

HELO AMCRISTW


0

j 没有被赋值。我猜它被初始化为0,所以没有异常。

如果你把第二个循环改成 for(int j=0; j< str.length(); j++) 它仍然不会工作,它不会打印任何在字符串中重复的字母。

所以想一想 j 需要迭代的范围。如果你明白我的意思,你想打印任何在字符串中尚未出现过的字母。


这只是我的程序中的一个例子,是正确的。问题已经得到了回答。 - Christos Michael
@ChristosMichael:在这种情况下,最好接受最能回答你问题的答案。这可以帮助未来的访问者快速找到解决问题的有效方法。请查看【当有人回答我的问题时我该怎么做?】(http://stackoverflow.com/help/someone-answers)。 - IInspectable
我的回答针对您提供的代码中的错误,我怎么知道您在程序中使用了什么。而且,我假设您想解决实现逻辑中的问题,没有意识到您有其他选项可用于使用众所周知的数据结构。 - Miserable Variable

0

很遗憾,在Java 8中没有字符流,但这是一种Java 8的方法:

str.chars().distinct().mapToObj(c -> (char) c).collect(Collectors.toList());

这种方法可能不太高效,但它是一行可读的代码,并展示了流的强大之处。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接