-
-
Notifications
You must be signed in to change notification settings - Fork 9.1k
en/lcci/1.6/ #3920
-
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 1 comment
-
// My approach is to do this question using single iteration ..
// My intuition is rau a loop from index 1 and check prev ele is same as current element if then increase the count.. and if prev element is not same diff we simply add the the prev alphabet and its count .to add count we need to convert the number into string using to_string function
#include <bits/stdc++.h>
using namespace std;
string compress(const string &s,int n ) {
int cnt = 1;
string comp;
for(int i = 1;i<n;i++){
if(s[i] == s[i-1]){
cnt++;
}else{
comp +=s[i-1];
comp += to_string(cnt);
cnt = 1;
}
}
comp += s[n-1];
comp += to_string(cnt);
return comp;
}
int main(){
string s = "aabbcccdb";
int n = s.size();
string ans = compress(s,n);
cout<<ans<<endl;
return 0;
}
Beta Was this translation helpful? Give feedback.
All reactions
-
👍 1