You are given a string that comprises of lower case alphabets (a-z), upper case alphabets (A-Z), numbers, (0-9), and special characters like !,-.; etc.
You are supposed to find out which character occurs the maximum number of times and the number of its occurrence, in the given string. If two characters occur an equal number of times, you have to output the character with the lower ASCII Value.
For example, if your string was: aaaaAAAA, your output would be: A 4, because A has lower ASCII value than a.
Example:
Input: str = "Pulkit is a dog!!!!!!!!!!!!"
Output: ! 12
Approach
C++
#include <bits/stdc++.h>using namespace std;bool cmp(pair<int, char> a, pair<int, char> b){if (a.first == b.first)return a.second > b.second;return a.first < b.first;}void maximumOccurrence(string str){int n = str.size();int i = 0;map<char, int> mp;while (i < n){mp[str[i]]++;i++;}vector<pair<int, char>> v;for (auto it = mp.begin(); it != mp.end(); it++)v.push_back({it->second, it->first});sort(v.begin(), v.end(), cmp);cout << v[v.size() - 1].second<< " " << v[v.size() - 1].first << "\n";}int main(){string str = "Pulkit is a dog!!!!!!!!!!!!";maximumOccurrence(str);return 0;}
No comments:
Post a Comment