Print duplicate characters in a string
We have a string expression consisting of various characters in it. We want to count the repeated characters in this string and print it.
Example
String expression = "test string";
Here, the character 't' appears 3 times and 's' appears 2 times
Approach
- Create an empty Map to store character counts.
- Loop through each character in the input string.
- For each character encountered:
- Check if it's already in the data structure (the map).
- If it's not in the map, add it to the map with a count of 1.
- If it's already in the map, increment its count by 1.
- After processing the entire string:
- Examine the map.
- Identify characters with counts greater than 1; these are duplicates.
- Print or store the duplicate characters identified.
Complexity
- Time Complexity: O(N), where N is the length of the input string.
- Space Complexity: O(K), where K is the size of the map.
Java Code
import java.util.HashMap;
import java.util.Map;
public class CountRepeatedChars {
public static void printDuplicateCharactersWithCount(String inputString) {
char[] characters = inputString.toCharArray();
Map<Character, Integer> charCountMap = new HashMap<>();
// Count the occurrences of each character in the string
for (char c : characters) {
if (Character.isLetter(c)) { // Ignore non-letter characters if desired
charCountMap.put(c, charCountMap.getOrDefault(c, 0) + 1);
}
}
// Print characters with counts greater than 1 (duplicates)
for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()) {
if (entry.getValue() > 1) {
System.out.println("Character: " + entry.getKey() + ", Count: " + entry.getValue());
}
}
}
public static void main(String[] args) {
String inputString = "test string";
System.out.println("Duplicate characters in string \"" + inputString + "\" with their counts:");
printDuplicateCharactersWithCount(inputString);
}
}
Output
Duplicate characters in string "test string" with their counts:
Character: s, Count: 2
Character: t, Count: 3
Thanks for feedback.