number of disnict characters of a string code example
Example 1: finding no of unique characters in a string c++
int countDistinct(string s)
{
unordered_map<char, int> m;
for (int i = 0; i < s.length(); i++) {
m[s[i]]++;
}
return m.size();
}
Example 2: find unique characters in java
String str = "abbcdddefffggghjilll";
String [] arr = str.split("");
Map<String, Integer> mapStr = new LinkedHashMap<>();
for (int i=0 ; i < arr.length ; i++){
if (!mapStr.containsKey(arr[i])){
mapStr.put(arr[i],1);
} else{
mapStr.put(arr[i],mapStr.get(arr[i])+1);
}
}
for (Map.Entry<String,Integer> map : mapStr.entrySet()) {
if(map.getValue()==1) {
System.out.print(map.getKey());
}
}