为了将来参考,StackOverflow 通常要求您发布您拥有的内容,并寻求改进建议。
因为它不是一个活跃的一天,我很无聊,我已经为你做了这个。这段代码非常高效,并且没有使用高级数据结构。我这样做是为了让您更容易理解它。
请尝试理解我在做什么。学习是 StackOverflow 的目的。
我在代码中添加了注释以帮助您学习。
private String removeDuplicates(String keyword){
//stores whether a character has been encountered before
//a hashset would likely use less memory.
boolean[] usedValues = new boolean[Character.MAX_VALUE];
//Look into using a StringBuilder. Using += operator with strings
//is potentially wasteful.
String output = "";
//looping over every character in the keyword...
for(int i=0; i<keyword.length(); i++){
char charAt = keyword.charAt(i);
//characters are just numbers. if the value in usedValues array
//is true for this char's number, we've seen this char.
boolean shouldRemove = usedValues[charAt];
if(!shouldRemove){
output += charAt;
//now this character has been used in output. Mark that in
//usedValues array
usedValues[charAt] = true;
}
}
return output;
}
例子:
//output will be the alphabet.
System.out.println(removeDuplicates(
"aaaabcdefghijklmnopqrssssssstuvwxyyyyxyyyz"));