Skip to main content
Code Review

Return to Question

edited tags
Link
200_success
  • 145.5k
  • 22
  • 190
  • 478
Source Link
Fihop
  • 1k
  • 4
  • 20
  • 31

Run Length Encoding

Given an input string, write a function that returns the Run Length Encoded string for the input string.

For example, if the input string is "wwwwaaadexxxxxx", then the function should return "w4a3d1e1x6′′.

The following is my implementation:

string length_encoding(const string& s)
{
 char c = ' ';
 int num = 0;
 string result;
 string::const_iterator it = s.begin();
 for(; it != s.end(); ++it)
 {
 if(*it!=c)
 {
 if(num!=0)
 {
 stringstream ss;
 ss << num;
 string num_s(ss.str());
 result += num_s;
 }
 
 c = *it;
 result.push_back(c);
 
 num = 1;
 }
 else
 {
 num++;
 } 
 }
 
 stringstream ss;
 ss << num;
 string num_s(ss.str()); 
 result += num_s;
 
 return result;
}
lang-cpp

AltStyle によって変換されたページ (->オリジナル) /