🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
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
Initialize a Map: Use a
LinkedHashMapto store each character of the string along with its occurrence count. TheLinkedHashMapmaintains the order of insertion.Iterate Through the String: Convert the string into a character array and populate the map with character counts as you iterate through the array.
Count Repeated Characters: Traverse the entries of the
LinkedHashMapand count the characters with a count greater than1.Return the Result: Return the total count of repeated characters.
Method 2: Using an Array
Initialize an Array: Use an array of size
256(assuming ASCII characters) to store the frequency of each character.Iterate Through the String: Convert the string into a character array and update the frequency in the array.
Count Repeated Characters: Traverse the array and count the characters with a frequency greater than
1.Return the Result: Return the total count of repeated characters.
Method 3: Using Set and List
Initialize a Set and a List: Use a
Setto keep track of seen characters and aListto track repeated characters.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 theListof repeated characters. Otherwise, add it to theSet.Return the Result: Return the size of the
Listof 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
- Input String: The input string
"programming"is passed to the method. - Map Initialization: A
LinkedHashMapis initialized to store characters and their counts. - 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}.
- Counting Repeated Characters: The program counts the characters with more than one occurrence, resulting in 3 (
'r','g', and'm'). - 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
- Input String: The input string
"swiss"is passed to the method. - Array Initialization: An array of size 256 is initialized to track the frequency of each character.
- 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.
- Counting Repeated Characters: The program counts the number of characters that have a frequency greater than 1, which is 1 (
's'). - 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
- Input String: The input string
"abcd"is passed to the method. - Set and List Initialization: A
Setis used to track seen characters, and aListis used to store repeated characters. - Counting Characters:
- The characters
'a','b','c','d'are added to theSetas they are encountered. - No character is repeated, so the
Listremains empty.
- The characters
- Counting Repeated Characters: The size of the
Listof repeated characters is 0. - Output: The program prints
"Number of repeated characters: 0".
Summary of Outputs
For the input
"programming"using Method 1:Number of repeated characters: 3For the input
"swiss"using Method 2:Number of repeated characters: 1For 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
- Java Program to Find the First Non-repeated Character in a String
- Java Program to Check Palindrome String
- Java Program to Find Duplicate Characters in a String
- Java Program to Find Duplicate Words in a String
- Java Program to Find All the Permutations of a String
- Java Program to Count Occurrences of Words in a String
- Java Program to Count the Occurrences of Each Character
- Java Program to Count Vowels and Consonants in a String
- Java program to Count the Number of Duplicate Words in a String
- Java Program to Count Number of Words in Given String
- Java Program to Count the Number of Occurrences of Substring in a String
- Java Program to Count the Occurrences of Each Character in String
- Java Program to Merge Two String Arrays
- Java Program to Remove Duplicate Words from String
- Java Program to Reverse a String(5 ways)
- Java Program to Reverse Each Word of a String
- Java Program to Swap Two Strings
- How to Check if the String Contains Only Digits
- How to Check if the String Contains Only Letters
- How to Check If the String Contains Only Letters or Digits
- Java Program to Swap Two Strings Without Using Third Variable
Comments
Post a Comment
Leave Comment