Java Program to find duplicate characters count in a string - The Coding Shala
Home >> Java Programs >> Find duplicate characters count in a string
Other Posts You May Like
In this post, we will learn how to find duplicate characters count in a string and will write a Java program to find duplicate characters and their count.
Java Program to find duplicate characters count in a String
Problem
A string is given, you have to find all the duplicate characters in the string and need to return their count.
Example 1
Input: "aabb"
Output: a 2
b 2
Approach 1
We need to count the occurrence of each character in the given string. If the count is more than 1(one) then it's a duplicate character and we need to return that.
Java Program:
import java.util.*; class Main { public static void duplicate(String str) { int[] arr = new int[26]; for(int i=0; i<str.length(); i++) { int index = str.charAt(i) - 'a'; arr[index] = arr[index]+1; } for(int i=0; i<26; i++){ if(arr[i] > 1){ char c = (char)(i + 'a'); System.out.println("duplicate char "+c+" count is "+arr[i]); } } } public static void main(String[] args) { String s1 = "abcdaefghccabcda"; duplicate(s1); } }
- Add two Numbers in Java
- Add Binary Java Program
- Sum of digits of a number
- Two Sum Problem
- How to reverse a string in Java
Comments
Post a Comment