Problem : You have given an input String, write a program to print all the duplicates from input String. For example if given String is "Java" then your pogrom should print "a", and if given String is "C++" then your program should print "+". If String doesn't contain any duplicate then it should print nothing e.g. if you pass "Python" or "Ruby", it should print nothing.
How to Print Duplicates from a Given String in Java? [Solution]
General way to find the duplicate character is either by using hash table or a Set data structure in Java. Since Set doesn't allow duplicate, it return false if you add a character which is already present, that's your duplicate.
Same logic works for Hashtable as well, you can iterate over characters of String and build a HashMap, which contains number of times a character is appearing, now print all the characters for which the count is more than 1.
This problem is actually same as printing duplicates from array. Why? because String is nothing but a character array. You can get the character array from String by using toCharAray() method, as shown here.
Here is a nice diagram to visualize this problem :
Printing all duplicates using HashSet
import java.util.HashSet;
import java.util.Set;
public class PrintDuplicates {
public static void printDuplicatesUsingSet(String str) {
Set seen = new HashSet<>();
Set duplicates = new HashSet<>();
for (char c : str.toCharArray()) {
if (!seen.add(c)) {
duplicates.add(c);
}
}
System.out.println("Duplicates: " + duplicates);
}
}
Print all duplicates using HashMap
import java.util.HashMap;
import java.util.Map;
public class PrintDuplicates {
public static void printDuplicatesUsingMap(String str) {
Map charCount = new HashMap<>();
for (char c : str.toCharArray()) {
charCount.put(c, charCount.getOrDefault(c, 0) + 1);
}
System.out.print("Duplicates: ");
for (Map.Entry entry : charCount.entrySet()) {
if (entry.getValue() > 1) {
System.out.print(entry.getKey() + " ");
}
}
}
}
That's all about how to print duplicate characters from String in Java. If you know how to find duplicate elements in array then this problem is a cake walk, because its nothing but a special case of that problem. If Interviewer says that String always contain ASCII characters then you can also use array but using hashtable is more convenient.
No comments :
Post a Comment