Header Ads Widget

Character with their frequency | Capgemini coding question

 Character with their frequency | Capgemini coding question

Problem statement :-

The students are given a string with multiple characters that are repeated consecutively. You’re supposed to reduce the size of this string using mathematical logic given as in the example below  .

Sample input:

aabbbbeeeeffggg

Sample output:

a2b4e4f2g3

Input:

 abbccccc 

Output:

 ab2c5

C++ Code:-

#include<bits/stdc++.h>
using namespace std;

void printstring(char str[],int n)
{
int fre[26]={0};
for(int i=0;i<n;i++)
{
fre[str[i]-97]++;
}
string ans="";
for(int i=0;i<26;i++)
{
if(fre[i]>0)
{
char ch=i+97;
ans+=ch;
if(fre[i]>1)
ans+=to_string(fre[i]);

}
}
cout<<ans;
}

// Driver function
int main()
{
char s[5000];
cin>>s;
int len=strlen(s);
printstring(s,len);
return 0;
}

Python code:

def findchar(s1,n):
s2=""
l=list(s1)
d=dict()
for i in range(n):
if l[i] in d.keys():
d[l[i]]+=1
else:
d[l[i]]=1
for j in d.keys():
if d.get(j)>1:
s2+=j
s2+=str(d.get(j))
else:
s2+=j
return s2
s=input()
print(findchar(s,len(s)))

Wipro :-

Infytq :-

Key Points;-

Hackerrank:-


C-tutorial:-

See more:-