what is wrong in this code? It is not passing two test cases
String compression
hello @shubhangis248
the logic is not correct.
u only have to compress consecutive same characters.
for example->
aabbaaac is compressed as a2b2a3c1
Approach
- Take the first character of the present string and store it in say βchβ. Start iterating over the string and obtain the count of this character occurring consecutively from this point.
- Obtain the answer for remaining string recursively.
- Return ch+countOfCh+recursiveResult .
#include <bits/stdc++.h>
using namespace std;
string compress(string s)
{
if (s.size() == 0)
{
return "";
}
char ch = s[0];
int i = 1;
while (i < s.size() && s[i] == ch)
{
i++;
}
string ros = s.substr(i);
ros = compress(ros);
string charCount = to_string(i);
return ch + charCount + ros;
}
int main()
{
string s;
cin >> s;
cout << compress(s) << endl;
return 0;
}