×

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

Grepcode Java util date

What is java.util.Date Class? The date and time in Java are provided through the java.util.Date class. If you imported java.util, it could be helpful. Use the Java.util.Date class to implement this class...

4 minutes read.

Abstract Class Program in Java

Abstract Class Program in Java Abstraction is a technique by which a developer hides the implementation details from the user and shows only the functionality.It is not only confined to the...

6 minutes read.

Java Numbers

We use primitive data types like byte, int, long, double, etc to work with the numbers, When we need objects, we use wrapper class like Integer, Double, Long, Byte, etc....

2 minutes read.

Java Integer toUnsignedString() method

The toUnsignedString() method of Java Integer class returns a string representation of the argument as an unsigned decimal value. The second syntax returns a string representation of the given argument as...

2 minutes read.

If Condition in Lambda Expression Java

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single-method interface using an expression....

4 minutes read.

Array and String based questions in Java

1. What is an Array in Java? A collection of identical data types is referred to as an array. There can be no separate data kinds. It supports the storage of...

4 minutes read.

Java Integer toOctalString() method

The toOctalString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 8. Syntax public static String toOctalString (int  i) Parameters The parameter ‘i’ represents...

1 minute read.

How to calculate time complexity of any program in Java

Java : Java's syntax and principles are derived from the C and C++ languages. We know that java is one of the programming language. The main feature of java which is...

3 minutes read.

Bellman Ford Algorithm in Java

Numerous algorithms have been used in dynamic programming to determine the shortest path inside a graph. Among them are Floyd, all-pair shortest path problem, Breadth First Search, Depth First Search,...

6 minutes read.

Nth node from the end of the Linked list in Java

In talks with leading IT organizations like Google, Amazon, TCS, Accenture, etc., this extremely intriguing subject is constantly brought up. The goal of the problem-solving exercise is to evaluate the...

6 minutes read.

How to add double quotes in a string in Java

Strings are indicated using double-quotes. Double quotes are not printed; the values inside the double quotes are printed. There are different methods for adding double quotes to the string, such...

2 minutes read.

Deque in Java

Deque in java collections with Example Deque is short for “double-ended queue.” It is a linear collection that extends the Queue interface and supports insertion and deletion of the element at both the...

3 minutes read.

Display List of TimeZone with GMT and UTC in Java

It is vital to establish the right TimeZone in Java code when working with dates for Daylight Saving Time. In this part, we will present the time zones with GMT. TimeZone Those...

5 minutes read.

Add numbers represented by Linked Lists in Java

For calculating the sum of the two numbers that are represented by a linked list, and then store the result in a new linked list. A linked list's head node...

7 minutes read.

Java Thread Dump Analyzer

Thread: A thread is a PC program that is stacked into the PC's memory and is under execution. It tends to be executed by a processor or a bunch of processors....

15 minutes read.

Reentrant Lock in Java

The Lock interface is implemented by the ReentrantLock class, which also provides methods for synchronising access to shared resources. The code that controls the resource has calls to the lock...

4 minutes read.

Sleep Time in Java

Sleep is amethod in java that is related to thread class and it is a concept of multithreading and is used to stop the execution of the current thread a...

4 minutes read.

Array and String with Examples in Java

Array in Java: An array in Java is a group of variables with similar types that have a common name. The arrays used in Java differ from those used in C/C++. Key...

6 minutes read.

Java Generate UUID

What java Generate UUID? A 128-bit long value that is universally unique serves as the basis for the terms UUID (Universally Unique Identifier) and GUID (Globally Unique Identifier). Hexadecimal (octet) digits...

5 minutes read.

Java Math pow() Method

The pow() method of Math class returns the value of first argument raised to the power of second argument i.e. ab. Syntax: public static double pow(double a, double b) Parameters: The parameters ‘a’ and...

3 minutes read.