Friday, 3 December 2021

Q12_Program to find maximum and minimum occurring character in a string

max_min

Program to find maximum and minimum occurring character in a string

In this program, we need to count each character present in the string and find out the maximum and minimum occurring character. Grass is greener on the other side In above example, character 'a' is occurred only once in the string. So, it is minimum occurring character and is highlighted by red. Character e has occurred maximum number of times in the entire string i.e. 6 times. Hence, it is the maximum occurring character and is highlighted by green.

string 1

Remove white spaces

string 2

Removewhitespaces

Program

class max_min {

  public static void main(String[] args)   {

    //declare string

   String str1="grass is greener on the other side";

   int [] freq = new int [str.length()];

   char minChar = str.charAt(0), maxChar = str.charAt(0);

   int i, j, min, max;

   char string[] = str.toCharArray();

   for (i = 0; i < string.length; i++) {

         freq[i] = 1;

      for (j = i+1; j < string.length; j++) {

            if (string[i] == string[j] && string[i] != ' ' && string[i] != '0') {

               freq[i]++;

               string[j] = '0';

            }

      }

   }

   min = max = freq[0];

   for ( i = 0; i < freq.length; i++) {

      if (min > freq[i] && freq[i] != '0') {

         min = freq[i];

         minChar = string[i];

      }

       if (max < freq[i]) {

         max = freq[i];

         maxChar = string[i];

      }

   }

   System.out.println( "Minimum occurring character: " + minChar);

   System.out.println( "Maximum occurring character: " + maxChar);

    }

   }

output

Minimum occurring character: a Maximum occurring character: e

Theory

No comments:

Post a Comment

How do you select data from a table in SQL?

Create Table How do you select data a table in SQL? The SELECT statement is used to se...