Skip to content

Instantly share code, notes, and snippets.

@Shivamy2
Last active February 1, 2021 15:31
Show Gist options
  • Save Shivamy2/780a3baf55f3c4a36c6d1855853acae4 to your computer and use it in GitHub Desktop.
Save Shivamy2/780a3baf55f3c4a36c6d1855853acae4 to your computer and use it in GitHub Desktop.
// Time Complexity: O(n)
// Space Complexity: O(n)
// n is the length of the string
// In JAVA
import java.util.HashMap;
import java.util.Map;
class Definition {
public static Map<Character, Integer> countDuplicateCharacters(String string) {
var resultMap = new HashMap<Character, Integer>();
// write your code here ...
for(int i=0; i<string.length(); ++i) {
if(string.charAt(i) == ' ') continue;
if(resultMap.containsKey(string.charAt(i))) {
resultMap.put(string.charAt(i), resultMap.get(string.charAt(i))+1);
} else {
resultMap.put(string.charAt(i), 1);
}
}
return resultMap;
}
}
class Duplicates {
public static void main(String[] args) {
String message = "Competitive Programming Can Be A Little Bit Tricky!";
Definition definition = new Definition();
System.out.println(definition.countDuplicateCharacters(message));
/*
definition.countDuplicateCharacters(message).entrySet().forEach(entry -> {
if(entry.getValue() == 1 ) {
System.out.println(entry.getKey());
}
});
*/
}
}
// In C++
#include<bits/stdc++.h>
using namespace std;
unordered_map<char, int> countDuplicateCharacters(string);
int main() {
int count=0;
// Printing map
for(auto items : countDuplicateCharacters("Competitive Programming Can Be A Little Bit Tricky!")) {
if(items.second > 1) {
count++;
cout << items.first << " " << items.second << endl;
}
}
if(count==0) cout << "No Characters Are Repeating" << endl;
}
// Definition
unordered_map<char, int> countDuplicateCharacters(string str) {
unordered_map<char, int> resultMap;
for(auto chars : str) {
//ignoring space
if(chars == ' ') continue;
resultMap[chars]++;
}
return resultMap;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment