Saturday, September 16, 2023

 Print repeated characters of a String



When solving this problem, we need to think about how we can count the times each character appears in the String, so that we can say (if this char appears more than 1 time - it is a duplicate and print it.)

The best solution would be to use HashMap in order to keep track of the number of times each character appears in a String.

Here is the implementation in Java:

public class DevPrimer {

public static void main(String[] args) {

printDuplicates("deev primmerr");
}

public static void printDuplicates(String str) {
Map<Character, Integer> map = new HashMap<>();

for (int i = 0; i < str.length(); i++) {

// if char already exists, increment the integer counter by one,
// if do no exists, add it and set the value to 1
if (map.containsKey(str.charAt(i))) {
map.put(str.charAt(i), map.get(str.charAt(i)) + 1);
} else {
map.put(str.charAt(i), 1);
}
}

// print only the keys that have value > 1
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
if (entry.getValue() > 1) {
System.out.print(entry.getKey() + " ");
}
}
}
}

Time complexity is O(n). Space complexity is also O(n) since we are creating a Map that requires additional space in memory.




No comments:

Post a Comment