×

How to find characters with the maximum number of times in a string java

Problem statement

In this problem, users want to find the maximum count of a character from the string and return the character along with its count. Your task is to create a java program that contains the logic to solve this issue.

Solution

Approach - 1 : This problem can be done using hashing technique. You can use the hash map. You need to pass character as key record and integer as value record while creating a hash map. Now the logic is you must store the characters of the given string in the key record. And need to store the count of each character of the string in their respective key-value record. If you encounter the character again, then you need to increment the frequency count of that character in the hash map. You need to traverse the hash map. You need to compare the frequencies of each character and find the maximum frequency. Now store the index of character (say i) at which you got maximum frequency, and finally, you need to print the character at ith index along with its count.

Example 1.

import java.io.*;
import java.util.*;
import java.lang.*;
public class Main
{
public static void main (String[] args) {
Scanner sc=new Scanner (System.in);
        System.out.println("Please enter the String:");
String repString = sc.next();
FrequencyString StringFreq = new FrequencyString();
     StringFreq.Frequency (repString);
}
}
class FrequencyString
{
    void Frequency (String s)
    {
        HashMap<Character,Integer> Freq=new HashMap<>();
        for (int i=0;i<s.length();i++)
        {
            if (Freq.containsKey (s.charAt (i)))
            {
                Freq.put (s.charAt(i),Freq.get (s.charAt (i))+1);
            }
            else
            {
                Freq.put (s.charAt (i),1);
                
            }
        }
        int max = 0;
        int prevMax = 0;
        int index = 0;
        for (int i=0; i < s.length (); i++)
        {
            prevMax = Freq.get(s.charAt(i));
            if (max <prevMax)
            {
                max = prevMax;
                // storing the new maximum count of a 
                // character if it exists in the string.
                index = i; 
                // storing the index of maximum repeated character from the String.
            }
        }
        System.out.println (s.charAt (index)+"->"+max);
        // printing the max repeated character and its count.
    }
}
How To Find Characters With The Maximum Number Of Times In A String Java

In the above output, you can see the maximum repeated character from the string. But if the frequency of each character is the same, the above code will output the first character of the string.

How To Find Characters With The Maximum Number Of Times In A String Java

Now let us consider the word "Funbun" you can see that 'u' and 'n' are repeated twice. In these cases, you will output the first max repeated character.

How To Find Characters With The Maximum Number Of Times In A String Java

Time complexity: O(N)

Space complexity: O(N)

Approach - 2 : This is a brute force approach where you will take an array to store the frequency of each character in the string. You will need to compare every character of the string with each other. Then after you will have to traverse the frequency array along with the character array. When you find the maximum from the frequency array, then you will have to return the character at that index along with its count.

Example 2.

import java.io.*;
import java.util.*;
import java.lang.*;


public class Main
{
public static void main ( String [] args) {
Scanner sc = new Scanner ( System.in);
System.out.println("enter the string to get max repeated character");
String repString = sc.next (); // string input 
Jtp StringFreq = new Jtp ();
     StringFreq.Frequency ( repString );
}
}
class Jtp
{
    void Frequency ( String s )
    {
        int [] freq = new int [s.length()];  
        char [] str = s.toCharArray();// string to char array 
        for (int i = 0 ; i < s.length () ; i++)
        {
            int c = 1;
            for (int j = i+1; j < s.length(); j++)
            {
                if ( str [i] == str[j] ) // comparing each characterof string with other 
                {
                    c++;
                    str [j] = '0';
                }
            }
            freq [i] = c;
        } 
        int max = 0;
        int prevMax = 0;
        int index = 0;


        for (int i = 0;  i < freq.length ;i++)
        {
           prevMax = freq[i];
            if (max <prevMax)
            {
                max = prevMax;
                // storing the new maximum count of a 
                // character if it exists in the string.
                index = i; 
                // storing the index of maximum repeated character from the String.
            }
        }
        System.out.println ( str[index] +" -> " + max); // printing the max repeated chracter with count
    }
}

Time complexity: O(N^2)

Space complexity: O(N)

How To Find Characters With The Maximum Number Of Times In A String Java How To Find Characters With The Maximum Number Of Times In A String Java How To Find Characters With The Maximum Number Of Times In A String Java

Related Topics

Hierarchy of operators in Java

Operators are the most frequently used terminology in any area of programming, and it helps in various approaches to efficiently solve daily life problems by computer programming. The simple addition of...

4 minutes read.

Compile-time Error in Java

In java, the execution of a program is stopped due to the occurrence of some problem known as an error. Errors are illegal operations that are carried out by the...

4 minutes read.

XNOR operator in Java

The opposite of the binary equivalent of XOR is given by XNOR. Truth table: XYXNOR001010100111 If the bits are the same, it returns 1, else it returns 0. Examples:  Input: 10 20 Output : 1 A Binary...

3 minutes read.

How to take Array Input in Java

In this tutorial, we will learn about how to take array input in Java. So, before taking inputs let us know what an array is first. Array: An array is a collection...

10 minutes read.

Java Interface Lock

A synchronisation method called the Lock interface is available as of JDK 1.5. It is comparable to a synchronised block but more complex and versatile. The package java.util.concurrent contains the...

4 minutes read.

String Array in Java

String Array in Java An array is alinear data structure that stores similar type of data. It allows us to store fixed number of elements.It can be of different data types...

6 minutes read.

Shift right zero Fill Operator in Java and Operator Shifting

Left shift operator ( << ) : The left shift operator is an operator which performs its action at the bits level of a binary Operator. That means when you perform...

4 minutes read.

Convert List to String in Java

We occasionally need to create a string from a list of characters. Since a string is only a collection of characters, a character array can be converted into a string....

6 minutes read.

House Numbers in Java

In this section, we will discuss about house number in Java. It is a sum of cubes, each of which has a dimension of h + 1. There is a...

3 minutes read.

public static void main string args meaning in java

In java main() method is the initial point for execution of the program. If a program doesn’t contain the main method, the program will not execute. JVM(java virtual machine) starts...

3 minutes read.

String isnullorempty in Java

What do you mean by String? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

How to override toString() method in Java?

Java is an object-oriented language. It only works with classes and objects. Thus, whenever we need to calculate, we need an object or objects that belong to the class. The Java method...

2 minutes read.

What is Core Java?

The fundamental Java, which includes the fundamental idea of the Java programming language, is referred to as "Core Java." The definition of "Core" is the core idea of something. Core...

3 minutes read.

How to get ASCII value of char in Java

Introduction: On this application, you will learn how to find and show the ASCII value of char in Java. That is done with the use of type-casting and also everyday...

4 minutes read.

Creating a Jar file in Java

The JDK's jar (Java Archive) tool offers the ability to produce jar files that can be executed. If you double-click a jar file that is executable, it will call the...

2 minutes read.

Java Case Keyword

Case keyword: In this article we are going to learn the concept of a java case keyword.Generally, java case keyword is used with the switch statements.Case keyword is implemented in conditional...

3 minutes read.

Virtual Function in Java

In the Operated Oriented Programming language, a virtual function or virtual method is a collection of functions that overrides the functionality of a function in an inheriting class with the same...

4 minutes read.

C# vs Java

Difference Between C# and Java C# and Java both languagesare popularly used programming languages. They both are derived from C/C++ programming and follow Object Oriented Programming approach. Even so, both these...

4 minutes read.

Group by in Java 8

By using this groupingBy() method, developers can directly able to perform the "GROUP BY" operation. The thing is, now, the Java 8 programming language allows the programmers to do this...

3 minutes read.

Java Open File

Java Desktop class give an open() strategy to open a filr. It has a place with a java.awt package. Work area execution is stage subordinate, so it is important to...

5 minutes read.