Initially I thought of using a set to compile a group of unique characters but that would be adding extra code executions. I figured that I can solve this rather easily by going back to the basics. You may see that as I am constructing a new string "uniq", I am using the indexOf() method to look up for a particular character in that string. A value less than 0 means that the character that we are looking for does not exist at that moment. So we are appending it to "uniq". Another problem solved :)
public static String removeDuplicates(String text){
StringBuffer uniq = new StringBuffer();
int len = text.length();
for (int i=0; i<len; i++) {
if (uniq.indexOf(Character.toString(text.charAt(i))) < 0) {
uniq.append(text.charAt(i));
}
}
return uniq.toString();
}
Update: The code is also available in Python in this entry
0 comments:
Post a Comment