Home › Forums › Programming › Run Length Encoding: Cpp
- This topic has 3 replies, 2 voices, and was last updated 12 years, 7 months ago by Satish.
Viewing 4 posts - 1 through 4 (of 4 total)
- AuthorPosts
- April 11, 2012 at 4:00 pm#1543SwathiMember
The Problem is on run length encoding.
Input : Output
AAAAAABCCCC : 6A1B14C
12344 : 11123124
Source: Problem Statement
April 12, 2012 at 7:30 am#1544SatishKeymaster#include < iostream > #include < string > using namespace std; string encodeRunLength(const string &st) { string res, ans; char prev = st[0]; int L = 0; for(string::const_iterator itr = st.begin(); itr != st.end(); ++itr) { if((prev == *itr) && L < 9){ ++L; }else{ res += static_cast<char>('0'+L); res += prev; prev = *itr; L = 1; } } res += static_cast<char>('0'+L); res += prev; char len, plen = '0'; for(string::iterator itr = res.begin(); itr != res.end(); ++itr) { len = *itr++; if(len == '1') { if(plen == '1'){ ans += (*itr); }else{ ans += '1'; ans += (*itr); } if(*itr == '1') { ans += '1'; } }else{ if(plen == '1') { ans += plen; } ans += len; ans += (*itr); } plen = len; } if(plen == '1'){ ans += '1'; } return ans; } int main(int argc, char **argv) { string st; while(getline(cin,st)) { cout << encodeRunLength(st) << endl; } return 0; }
April 12, 2012 at 7:33 am#1546SatishKeymastercorrect the spacing between the opening < and closing >
April 12, 2012 at 7:46 am#1547SatishKeymasterAlso Try this..
#include<iostream> #include<string> using namespace std; string check(char c) { string s=""; s+=c; if(c=='1') return "11"; else return s; } int main() { string s; while(getline(cin,s)) { if(s.size()) { int prevcount=0,count=1; char a=s[0]; for(int i=1;i<s.size();i++) { if(s[i]==a) { count++; if(count==9) { cout<<9<<a; prevcount=9; if(i<s.size()-1) { a=s[++i];count=1;} else count=0; } } else { if(prevcount==1) { if(count==1) cout<<check(a); else cout<<1<<count<<a; } else { if(count==1) cout<<1<<check(a); else cout<<count<<a; } prevcount=count; a=s[i];count=1; } } if(count!=0) { if(prevcount==1) { if(count==1) cout<<check(a)<<1; else cout<<1<<count<<a; } else { if(count==1) cout<<1<<check(a)<<1; else cout<<count<<a; } } } cout<<endl; } return 0; }
- AuthorPosts
Viewing 4 posts - 1 through 4 (of 4 total)
- You must be logged in to reply to this topic.