题目:给定一个包含ASCII码的字符串,利用下列规则进行编码
1)将子串中连续k个相同字符c编为kc
2)若子串长度为1,则1忽略。
实现一:整体编码完再输出
char * encoding_v1( char * str_in ) { char * str_out = new char[100]; memset( str_out, ‘/0’, sizeof(char) * 100 ); int freq = 1; char num[10] = { ‘/0’ }; for( int i = 0; str_in[i] != ‘/0’; ++i ) { if( str_in[i] == str_in[i+1] ) { ++freq; } else { if( freq > 1 ) { itoa( freq, num, 10 ); strcat( str_out, num ); } char s[] = { str_in[i], ‘/0’}; strcat( str_out, s ); freq = 1; } } return str_out; }
实现二:编码的同时逐步输出结果
void encoding_v2( char * str ) { int freq = 1; for( int i = 0; str[i] != ‘/0’; ++i ) { if( str[i] == str[i+1] ) { ++freq; } else { if( freq > 1 ) { cout << freq; } cout << str[i]; freq = 1; } } cout << endl; }
实现三:利用std::string类实现
void encode_v3( const string & s ) { int freq = 1; for( int j = 0; j < s.size(); j++ ) { if( s[j] == s[j+1] ) ++freq; else { cout << freq << s[j]; freq = 1; } } cout << endl; }
实现四:不是相邻两元素比较,而是与新串首字符比较。
void encode_v4( const string & s ) { string t; t = s[0]; int freq = 0; for( int i = 0; i < s.size(); ++i ) { if( s[i] == t[0] ) { ++freq; } else { printf( “%d%c”, freq, t[0] ); t[0] = s[i]; freq = 1; } if( i == s.size() – 1 ) printf(“%d%c”, freq, t[0] ); } printf(“/n”); }