标签:strong for ar amp size res ad ef
此类题目要明确两点:
1. 打表:用数组下标索引字符,同时注意如果从字符对应回数字:
int index = (str[i] >= ‘0‘ && str[i] <= ‘9‘) ? (str[i]-‘0‘-radix):(str[i]-‘a‘-radix + 10);
2. 注意低位在前还是高位在前,如果先来的是 低位*radix^i 即可。
3. 统计每几个radix进制数组成一位,利用bits来表示。。。
这破题主要是麻烦。。。
#include <assert.h>
#include <algorithm>
#include <vector>
using namespace std;
const int radix = 4;
string base = "";
string compress(const vector<int>& arr) {
string res = "";
int i, j, size = arr.size(), left, bits;
for (i = 1, j = 0; i*radix + radix < 36; i *= radix, ++j);
bits = j;
left = size - size / bits * bits;
size = size / bits * bits;
for (char ch = '0'; ch <= '9'; ++ch)
base.push_back(ch);
for (char ch = 'a'; ch <= 'z'; ++ch)
base.push_back(ch);
for (i = 0; i < size; i += bits) {
int index = 0, t = 1;
for (j = 0; j < bits; ++j) {
index = index + arr[i+j]*t;
t *= radix;
}
res.push_back(base[radix+index]);
}
for (i = 0; i < left; ++i)
res.push_back(arr[size+i]+'0');
return res;
}
vector<int> depress(const string& str) {
int len = str.length(), i = 0, j, bits;
for (i = 1, j = 0; i*radix + radix< 36; i *= radix, ++j);
bits = j;
vector<int> res;
for (i = 0; i < len; ++i) {
if (str[i]-'0' >= 0 && str[i]-'0' < radix)
res.push_back(str[i]-'0');
else {
int index = (str[i] >= '0' && str[i] <= '9') ? (str[i]-'0'-radix):(str[i]-'a'-radix + 10);
for (j = 0; j < bits; ++j) {
res.push_back(index%radix);
index = index/radix;
}
}
}
return res;
}
int main() {
int arr[] = {0,1,2,2,2,2,1,1,1,2,0,0,0,0,0,1};
vector<int> vec(arr, arr+sizeof(arr) / sizeof(int));
string str = compress(vec);
vector<int> res = depress(str);
return 0;
}
将n进制的数组压缩成字符串(0-9 a-z)同时解压,布布扣,bubuko.com
标签:strong for ar amp size res ad ef
原文地址:http://blog.csdn.net/taoqick/article/details/38502377