Sunday, July 7, 2019

Java Program 4: How to find the number of times each duplicate character repeated in the given string?

Let us understand the question with an example, we need to find the all the duplicate characters and how many times each duplicate character repeated.
  • Suppose "Selenium Java" is the given string then, 'e' and 'a' are the duplicate characters and 'e' repeated two times and 'a' also repeated two times.
  • If "Java Program" is the given string then, 'a' and 'r' are the duplicate characters and 'a' repeated thrice and 'r' repeated two times. 

Hope the question is clear now, lets try implementing the logic step by step.

Step 1: Read the string from the user using "Scanner" class as shown below.

Step 2: Convert the string into character array

Step 3: Define a HashMap. Loop through the character array and put them in the HashMap on below conditions

  • If the character present in the map as a key, increase the value by 1
  • It the character not in the map as a key, just put it in the map with value 1

Step 4: Now get the entry set, and verify the characters all the characters whose values are greater than or equal to 2.


Below is the code

Lets execute program and observe the result below.


You can see that we are getting the number of times each duplicate character repeating the in the given string.

#HappyLearning #HappyTesting

No comments:

Post a Comment

DevOps 01: What is DevOps and How it benefits organizations?

DevOps is a culture in an organization, where the development team and operations team help each other by sharing information, process and t...