Java Program to Count Number of Repeated Characters in a String

Introduction

In this guide, we will develop a Java program to count the number of repeated characters in a string. Counting repeated characters is a common task in string processing, useful in various applications like data analysis, text compression, and cryptography. We will explore different methods to achieve this, ensuring an efficient and clear solution.

Problem Statement

Given a string, the task is to count how many characters appear more than once in the string. The program should return the count of such repeated characters.

Example 1:

  • Input: "programming"
  • Output: 3 (The characters 'r', 'g', and 'm' are repeated)

Example 2:

  • Input: "swiss"
  • Output: 1 (The character 's' is repeated)

Example 3:

  • Input: "abcd"
  • Output: 0 (No characters are repeated)

Solution Steps

Method 1: Using LinkedHashMap

  1. Initialize a Map: Use a LinkedHashMap to store each character of the string along with its occurrence count. The LinkedHashMap maintains the order of insertion.

  2. Iterate Through the String: Convert the string into a character array and populate the map with character counts as you iterate through the array.

  3. Count Repeated Characters: Traverse the entries of the LinkedHashMap and count the characters with a count greater than 1.

  4. Return the Result: Return the total count of repeated characters.

Method 2: Using an Array

  1. Initialize an Array: Use an array of size 256 (assuming ASCII characters) to store the frequency of each character.

  2. Iterate Through the String: Convert the string into a character array and update the frequency in the array.

  3. Count Repeated Characters: Traverse the array and count the characters with a frequency greater than 1.

  4. Return the Result: Return the total count of repeated characters.

Method 3: Using Set and List

  1. Initialize a Set and a List: Use a Set to keep track of seen characters and a List to track repeated characters.

  2. Iterate Through the String: Convert the string into a character array. For each character, check if it is in the Set. If it is, add it to the List of repeated characters. Otherwise, add it to the Set.

  3. Return the Result: Return the size of the List of repeated characters.

Java Programs

Method 1: Using LinkedHashMap

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Java Program to Count Number of Repeated Characters in a String
 * Author: https://www.javaguides.net/
 */
public class RepeatedCharacterCount {

    public static int countRepeatedCharacters(String str) {
        Map<Character, Integer> characterCountMap = new LinkedHashMap<>();
        int repeatedCount = 0;

        // Populate the map with character counts
        for (char ch : str.toCharArray()) {
            characterCountMap.put(ch, characterCountMap.getOrDefault(ch, 0) + 1);
        }

        // Count repeated characters
        for (Map.Entry<Character, Integer> entry : characterCountMap.entrySet()) {
            if (entry.getValue() > 1) {
                repeatedCount++;
            }
        }

        return repeatedCount;
    }

    public static void main(String[] args) {
        String input = "programming";
        int result = countRepeatedCharacters(input);
        System.out.println("Number of repeated characters: " + result);
    }
}

Output for Method 1

For the input "programming", the output will be:

Number of repeated characters: 3

Step by Step Explanation for Method 1

  1. Input String: The input string "programming" is passed to the method.
  2. Map Initialization: A LinkedHashMap is initialized to store characters and their counts.
  3. Counting Characters:
    • 'p', 'r', 'o', 'g', 'a', 'm', 'i', 'n' are added to the map with their respective counts.
    • The map looks like this: {p=1, r=2, o=1, g=2, a=1, m=2, i=1, n=1}.
  4. Counting Repeated Characters: The program counts the characters with more than one occurrence, resulting in 3 ('r', 'g', and 'm').
  5. Output: The program prints "Number of repeated characters: 3".

Method 2: Using an Array

/**
 * Java Program to Count Number of Repeated Characters in a String
 * Author: https://www.javaguides.net/
 */
public class RepeatedCharacterCountArray {

    public static int countRepeatedCharacters(String str) {
        int[] charFrequency = new int[256];
        int repeatedCount = 0;

        // Populate the array with character frequencies
        for (char ch : str.toCharArray()) {
            charFrequency[ch]++;
        }

        // Count repeated characters
        for (int count : charFrequency) {
            if (count > 1) {
                repeatedCount++;
            }
        }

        return repeatedCount;
    }

    public static void main(String[] args) {
        String input = "swiss";
        int result = countRepeatedCharacters(input);
        System.out.println("Number of repeated characters: " + result);
    }
}

Output for Method 2

For the input "swiss", the output will be:

Number of repeated characters: 1

Step by Step Explanation for Method 2

  1. Input String: The input string "swiss" is passed to the method.
  2. Array Initialization: An array of size 256 is initialized to track the frequency of each character.
  3. Counting Characters:
    • The array is updated based on the frequency of each character.
    • For example, the count for 's' will be 3, 'w' and 'i' will each be 1.
  4. Counting Repeated Characters: The program counts the number of characters that have a frequency greater than 1, which is 1 ('s').
  5. Output: The program prints "Number of repeated characters: 1".

Method 3: Using Set and List

import java.util.HashSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Java Program to Count Number of Repeated Characters in a String
 * Author: https://www.javaguides.net/
 */
public class RepeatedCharacterCountSetList {

    public static int countRepeatedCharacters(String str) {
        Set<Character> seenCharacters = new HashSet<>();
        List<Character> repeatedCharacters = new ArrayList<>();

        // Populate the Set and List
        for (char ch : str.toCharArray()) {
            if (seenCharacters.contains(ch)) {
                if (!repeatedCharacters.contains(ch)) {
                    repeatedCharacters.add(ch);
                }
            } else {
                seenCharacters.add(ch);
            }
        }

        return repeatedCharacters.size();
    }

    public static void main(String[] args) {
        String input = "abcd";
        int result = countRepeatedCharacters(input);
        System.out.println("Number of repeated characters: " + result);
    }
}

Output for Method 3

For the input "abcd", the output will be:

Number of repeated characters: 0

Step by Step Explanation for Method 3

  1. Input String: The input string "abcd" is passed to the method.
  2. Set and List Initialization: A Set is used to track seen characters, and a List is used to store repeated characters.
  3. Counting Characters:
    • The characters 'a', 'b', 'c', 'd' are added to the Set as they are encountered.
    • No character is repeated, so the List remains empty.
  4. Counting Repeated Characters: The size of the List of repeated characters is 0.
  5. Output: The program prints "Number of repeated characters: 0".

Summary of Outputs

  1. For the input "programming" using Method 1:

    Number of repeated characters: 3
    
  2. For the input "swiss" using Method 2:

    Number of repeated characters: 1
    
  3. For the input "abcd" using Method 3:

    Number of repeated characters: 0
    

Conclusion

These Java programs provide different methods to count the number of repeated characters in a string. Whether using a LinkedHashMap, an array, or a combination of Set and List, each approach offers a reliable solution for string processing tasks. The programs are efficient, handling edge cases effectively, and are well-suited for various applications.

Related Java String Programs with Output

Comments