Is there any efficient way (that not includes "contains" or "indexOf" methods) to remove duplicate characters (included) from a given String.
For example:
input: "abcdcb"
output: "ad"
input: "abracadabra"
output: "cd"
I have tried using RegEx but something got wrong:
public static String function(String str) {
return str.replaceAll("([a-z]+)\\1", "");
}
Edit: Longest, non efficient solution:
public static String function(String s) {
String result = "";
for (int i = 0; i < s.length(); i++)
if(s.length() - s.replace("" + s.charAt(i), "").length() == 1)
result += "" + s.charAt(i);
return result;
}
Map<Character, Integer>in which you will store how many times each character appeared. Then only collect those which appeared once.