top of page
Writer's pictureThe Tech Platform

How to Find Repeated Characters in Given String with Count in Java?


In order to solve this problem, You need to first check if a String contains any duplicate characters or not, and then if it contains any duplicate letters then find out how many times they appear in the given input String.


Your output should contain duplicate letters and their count. For example, if we pass "Java" as input then it should print duplicate letter = a, count = 2. Your program should be case insensitive, which means a and A should be counted as duplicate characters. Bonus marks for providing unit tests for this program.


Here are steps to solve this problem in the simplest way:


1) Covert the string into the upper case or lower case to handle case insensitive and obtain a character array from String using toCharArray() as shown below:


   char[] chars = input.toUpperCase().toCharArray(); 

2) Go through the character array and build the map with character and their count


3) Iterate through the map we have built-in previous space and print all characters whose count is greater than 1. They are repeated characters.


4) The time complexity of this solution is O(n) even though we are using two loops but they are not nested. This means that even if the length of String will increase exponentially, we will still use only two loops, not the N^2 loop.


5) The space complexity of this solution is also O(n) because we are using the additional hash table for storing character and their count whose size is directly proportional to the number of characters in the given string.


Java Program to find repeated characters and their frequency in String


For running this program, you can either accept input from the command line as shown in my example or you can just run the program in the Unit tests with pre-defined input.

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

/**  
* Write a Program in Java to find duplicate characters and their count?  * You should not use a library method to solve this problem, though you  * are free to use utility and collection classes.  
*  
* @author Javin Paul  
*/

public class DuplicateCharacterInString 
{
    public static void main(String args[]) 
    {
        System.out.println("Please enter a String");
        String input = null;
        
        while (!"EXIT".equals(input)) 
        {
            Scanner reader = new Scanner(System.in);
            
            // String input from the user             
            input = reader.nextLine();
            
           // get character array from String after converting the case
           // for case insensitive counting
            char[] chars = input.toUpperCase().toCharArray();
            
            // build map char -> count
            Map duplicates = new HashMap();
            for (char ch : chars) 
            {
                Integer oldCount = duplicates.get(ch);
                if (oldCount == null) 
                {                     
                    duplicates.put(ch, new Integer(1));
                } else {                     
                duplicates.put(ch, ++oldCount);
                }
              }
                
             // Iterate through Map to find duplicates
             Set> duplicateChars = duplicates.entrySet();
             for (Map.Entry entry : duplicateChars) 
             {
             if (entry.getValue() > 1) 
             {
             System.out.printf("Duplicate Character : %s, Count %d %n",                             
                 entry.getKey(), 
                 entry.getValue());
              }
           }
         }}
     }   


Output:

Please enter a String 
Java 
Duplicate Character: A, Count 2   

Sybase 
Duplicate Character: S, Count 2   

Programming 
Duplicate Character: G, Count 2 
Duplicate Character: R, Count 2 
Duplicate Character: M, Count 2   

Technology 
Duplicate Character: O, Count 2

"" 

Duplicate Character: ", Count 2   

************ 
Duplicate Character : *, Count 12   

MyYourRame 
Duplicate Character: R, Count 2 
Duplicate Character: M, Count 2 
Duplicate Character: Y, Count 2   
EXIT 

As you can see we have tested this Java program for different types of input like empty String, String with *, String containing duplicate letters in both upper and lower case, and some normal String, which contains duplicate characters. You can actually encapsulate them in different unit test cases.




Source: Java67


The Tech Platform

0 comments

Comentários


bottom of page