#include
#include
using namespace std;
int main() {
int i,l,c[10000]={0};
string s1;
cin>>s1;
int n=s1.size();
for(i=0;i<n;i++)
{
c[s1[i]-‘a’]++;
}
for(i=0;i<n;i++)
{
if(c[s1[i]-‘a’]!=0)
{
cout<<s1[i]<<c[s1[i]-‘a’];
}
c[s1[i]-‘a’]=0;
}
return 0;
}
All test cases not passing
Hey Shivansh! The problem in your approach is that it will fail for cases when a particular character appears at multiple places in the string. For eg: “aabccffaa”, here your code will just count all 'a’s at once and print:
a4b1c2f2 but the expected answer is a1b1c2f2a2. So, instead of counting at once and printing after that, try counting and printing while traversing at the same time.
psedocode for the approach:
for (int i = 0; i < n; i++) {
// take count of the current character as long as it is repeating
int count = 1;
while (i < n - 1 && str[i] == str[i + 1]) {
count++;
i++;
}
// As soon as we get a different character, print the count of the current character
cout << str[i] << count;
}
1 Like
If it helped you, please mark this doubt as resolved and also rate the response!