Find the maximum occurring character in given string.

2. Given an input string S, write a program to find the maximum occurring character in S. For example, if the input string is "tushita" then the program should return t.

Input: The first line contains an integer representing the size of S The second line contains the string S

Output: Maximum occurring character. If more than one character has maximum count then return the first character with the maximum count in the input string.

SOLUTION IN C

#include<stdio.h>
#include<string.h>
int main()
{
  char ch,str[100];
  int s,i,j,c=0,max=1;
  scanf("%d\n",&s);
  gets(str);
  for(i=0;i<s;i++)
  {
    c=0;
    for(j=0;j<s;j++)
    {
      if(i!=j&&str[i]==str[j])
      {
        c++;
      }
    }
    if(max<c)
    {
      ch=str[i];
      max=c;
    }
  }
  printf("%c",ch);
}

SOLUTION IN C++

#include<iostream>
#include<string>
using namespace std;
int main()
{
  string str;
  char ch;
  int s,i,j,c=0,max=1;
  cin>>s;
  cin.ignore();
  getline(cin,str);
  for(i=0;i<s;i++)
  {
    c=0;
    for(j=0;j<s;j++)
    {
      if(i!=j&&str[i]==str[j])
      {
        c++;
      }
    }
    if(max<c)
    {
      ch=str[i];
      max=c;
    }
  }
  cout<<ch;
}

No comments:

Post a Comment

Total Pageviews