gpt4 book ai didi

java - 在java中,从字符串中删除重复字符的最有效方法是什么?

转载 作者:行者123 更新时间:2023-12-02 04:52:28 24 4
gpt4 key购买 nike

我有一个辅助函数,可以查找字符串中重复字符的索引。现在删除这些重复项的最佳方法是什么?谢谢!

最佳答案

这是我所知道的最好的方法。它接受一个字符串,将其分成字符,将其放入哈希集(不重复,有序),然后打印(或者可以返回字符串。

这是列出的方法中最好的方法

String example = "thiscode";
char[] chars = example.toCharArray();
Set<Character> str = new LinkedHashSet<Character>();
for (char c : chars) {
str.add(c);
}

StringBuilder sb = new StringBuilder();
for (Character character : str) {
sb.append(character);
}
System.out.println(sb.toString());

或者:

public static String convert(String example){
char[] chars = example.toCharArray();
Set<Character> str = new LinkedHashSet<Character>();
for (char c : chars) {
str.add(c);
}

StringBuilder sb = new StringBuilder();
for (Character character : str) {
sb.append(character);
}
return sb.toString();
}

另一种方法:

    String example = "thiscode";
StringBuilder sb = new StringBuilder(example);
for (int i=0; i<example.length(); i++) //itterate throught the characters
if (!sb.toString().contains(example.charAt(i) + "")) //determine if its in the stringbuilder
sb.append(example.charAt(i)); //if not add it
example = sb.toString(); //take result
System.out.println(example);

效率低下,但易于实现

String example = "thiscode";
String empty = "";
boolean alphabet[] = new boolean[26];
for (char c : example.toCharArray())
if (alphabet[(int) ((c + "").toLowerCase().charAt(0) - 'a')] == false)
empty += c;
example = empty;
System.out.println(example);

希望这有帮助。

关于java - 在java中,从字符串中删除重复字符的最有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29090126/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com