Solution: Here is a solution to find duplicate characters in String.
- Create a HashMap and the character of String will be inserted as key and its count as value.
- If HashMap already contains char, increase its count by 1, else put char in HashMap.
- If the value of Char is more than 1, that means it is a duplicate character in that String.
Java Program to find duplicate Characters in a String:
import java.util.HashMap; import java.util.Map; import java.util.Set; public class DuplicateCharFinder { public void findIt(String str) { Map<Character, Integer> baseMap = new HashMap<Character, Integer>(); char[] charArray = str.toCharArray(); for (Character ch : charArray) { if (baseMap.containsKey(ch)) { baseMap.put(ch, baseMap.get(ch) + 1); } else { baseMap.put(ch, 1); } } Set<Character> keys = baseMap.keySet(); for (Character ch : keys) { if (baseMap.get(ch) > 1) { System.out.println(ch + " is " + baseMap.get(ch) + " times"); } } } public static void main(String a[]) { DuplicateCharFinder dcf = new DuplicateCharFinder(); dcf.findIt("India is my country"); } }
is 3 times i is 2 times n is 2 times y is 2 times