This program demonstrates finding duplicate characters from a string and displaying the number of repeating characters.
ImportJava.util.HashMap;ImportJava.util.Map;ImportJava.util.Set; Public classDetails { Public voidcountdupchars (String str) {//Create a HashMap objectMap<character, integer> map =NewHashmap<character, integer>(); //converting a string to a char array Char[] chars =Str.tochararray (); /*logic: Insert each character into the map, each element in the map is a combination of [key,value], * Key record character, and value records the number of occurrences of this character. * If CH is already present in the map, modify the number of occurrences of the character (original number + 1). * If CH is not in map, then CH is inserted into map, key is ch, value is 1*/ for(Character ch:chars) {if(Map.containskey (ch)) {map.put (ch, map.get ( ch))+1); } Else{map.put (ch,1); } } //get the key set of a mapset<character> keys =Map.keyset (); /*displays the number of characters that appear more than 1 times. */ for(Character Ch:keys) {
int n = map.get (ch);//Get the number of CH from mapif(N > 1) {System.out.println ("Char" +ch+ "" +n); } } } Public Static voidMain (String a[]) {Details obj=NewDetails (); System.out.println ("String:www.google.com"); System.out.println ("-------------------------"); Obj.countdupchars ("Www.google.com"); System.out.println ("\nstring:hello World"); System.out.println ("-------------------------"); Obj.countdupchars ("Hello World"); System.out.println ("\nstring: #@[email protected]!#$%!! %@"); System.out.println ("-------------------------"); Obj.countdupchars ("#@[email protected]!#$%!! %@"); }}
Getting Started with Java: the underlying algorithm finds duplicate characters from a string