Getting Started with Java: the underlying algorithm finds duplicate characters from a string

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.