Count Occurrences of Character in a String Java

Posted on Updated on

Problem Statement: Write a program to count occurrence of each character in a given string.

Test case 1:
Input : aabacghc
Output: a3b1c2g1h1

Test case 2:
Input: aaabbcccc
Output: a3b2c4

We suggest you think about a solution before reading further…

Solution:

  • Initialize an empty map.
  • Loop through each character of the string
  • If map contains character, increment counter
  • Else insert character with initial value(default 1) to the map.

Lets see an example to understand how this can be achieved.

Output

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.