行程编码(atoi函数)

 #include<iostream>
#include<string>
#include<vector>
using namespace std;
void jiema(string s)
{
cout << "解码之后为:" << endl;
for(int i = ; i < s.size(); i++)
{
if(s[i + ] == '*')
{
int j = i + ;
int len = ;
while(s[j + ] >= && s[j + ] <= )
{
len++;
j = j + ;
}
string temp = s.substr(i + , len);
int num = atoi(temp.c_str());
for(int k = ; k < num; k++)
{
cout << s[i];
}
i = j;
}
else
{
cout << s[i]; }
}
}
void bianma(string s)
{
vector<char>A;
int p = ;
int j = ;
for(; j < s.size();)
{
while(s[j] == s[j + ] && j < s.size())
{
p++;
j = j + ;
}
if(p >= )
{
A.push_back(s[j]);
A.push_back('*');
A.push_back(p);
p = ;
j = j + ;
}
else if(p < )
{
for(int k = ; k < p; k++)
{
A.push_back(s[j]);
}
p = ;
j = j + ;
}
}
cout << "编码之后为:" << endl;
for(int b = ; b < A.size(); b++)
{
if(A[b] >= && A[b] <= )
cout << int(A[b]);
else
cout << A[b];
}
cout << endl;
cout << "压缩比为:" << endl;
double y = double(A.size()) / s.size();
cout << y << endl;
}
void main()
{
cout << "请输入代码:①代码中含有数字表示需要解码解压缩②代码中不含数字表示需要编码压缩" << endl;
string s;
for(; cin >> s;)
{
int i = ;
for(; i < s.size(); i++)
{
if(s[i] >= && s[i] <= ) //解码
{
jiema(s);
break;
}
}
if(i == s.size())
{
bianma(s);
}
}
}
上一篇:[LeetCode] String to Integer (atoi) 字符串转为整数


下一篇:编写atoi库函数