performance - In java whats the most efficient way to remove duplicate characters from string? -
i have helper function finds indexes of duplicate characters in string. whats best way remove these duplicates? thanks!
this best way know it. takes string, separates characters, put hashset (nonrepeating, ordered) , prints (or return string.
this best way out of ones listed
string example = "thiscode"; char[] chars = example.tochararray(); set<character> str = new linkedhashset<character>(); (char c : chars) { str.add(c); } stringbuilder sb = new stringbuilder(); (character character : str) { sb.append(character); } system.out.println(sb.tostring());
alternatively:
public static string convert(string example){ char[] chars = example.tochararray(); set<character> str = new linkedhashset<character>(); (char c : chars) { str.add(c); } stringbuilder sb = new stringbuilder(); (character character : str) { sb.append(character); } return sb.tostring(); }
another way it:
string example = "thiscode"; stringbuilder sb = new stringbuilder(example); (int i=0; i<example.length(); i++) //itterate throught characters if (!sb.tostring().contains(example.charat(i) + "")) //determine if in stringbuilder sb.append(example.charat(i)); //if not add example = sb.tostring(); //take result system.out.println(example);
inefficient, easy implementation
string example = "thiscode"; string empty = ""; boolean alphabet[] = new boolean[26]; (char c : example.tochararray()) if (alphabet[(int) ((c + "").tolowercase().charat(0) - 'a')] == false) empty += c; example = empty; system.out.println(example);
hope helps.
Comments
Post a Comment