Re: delete repeated letters in a word
On Feb 9, 4:10 am, Michael Rauscher <michlm...@gmx.de> wrote:
spidey12345 wrote:
ok, fine, i am using hashset:)
but which function in there allow me to delete repeated values or 0,
that is not character
Why do you use an array? You don't even need a HashSet if speed doesn't
matter.
Untested (I even didn't tried to compile it) code:
public String removeDuplicateLetters( String word ) {
if ( word == null )
return null;
StringBuilder builder = new StringBuilder();
for ( int i = 0, n = word.length(); i < n; i++ ) {
String sub = word.substring(i,i+1);
if ( builder.indexOf(sub) == -1 )
builder.append(sub);
}
return builder.toString();
}
If you want to use a HashSet due to performance reasons the only thing
you'd have to replace is the if-condition and of course, you'd have to
add the element to the Set.
Bye
Michael
This might be a little better:
Its known to compile and run, for one thing.
public class Test2 {
public static void main(String[] args) {
final String s = "My string has a lot of duplicate letters";
final StringBuilder builder = new StringBuilder(s);
for (int i = 0; i < builder.length(); ++i) {
final String charStr =
Character.toString(builder.charAt(i));
int index = builder.indexOf(charStr, i+1);
while (index > i) {
builder.deleteCharAt(index);
index = builder.indexOf(charStr, index);
}
}
System.out.println(builder.toString());
}
}