Encoding and Decoding
EPI 7.12
Description:
Example:
encoding:
"aaabbdc" -> 3a2b1d1c
decoding:
1b3c2a -> bcccaa
Idea:
Code要写清楚。
Code:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int findNextChar(const string& input, int i){
char a=input[i];
int j=i;
for(; j<input.size(); ++j){
if(input[j] != input[i])
break;
}
return j;
}
string encoding(string input){
string result;
int i=0;
int j=0;
while(i<input.size()){
j = findNextChar(input, i);
result.push_back(j-i+'0');
result.push_back(input[i]);
i=j;
}
return result;
}
string decoding(string input){
string result;
int count=0;
for(int i=0; i<input.size(); i++){
if(isdigit(input[i])){
count = input[i]-'0';
}
else{
result.append(count, input[i]);
}
}
return result;
}
int main(){
cout<<encoding("aaabbdc")<<endl;
cout<<decoding("1b3c2a")<<endl;
}