Last active
February 1, 2021 15:31
-
-
Save Shivamy2/780a3baf55f3c4a36c6d1855853acae4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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