字符串压缩之C++实现
? ? 如輸入為:aaabbbccc則輸出為3a3b3c;如輸入為abbc,則輸出為a2bc。
? ? aaabbbccc ?----> ?3a3b3c
? ? abc ? ? ? ?----> ?abc
#include <iostream>
#include <string>
using namespace std;
int main()
{
? ? int cnt = 1;///cnt the number of every char
? ? int pos = 1;
? ? char tmp_A,tmp_B;
? ? string ori_str, sht_str;
? ? string::size_type ori_len;
? ? char c_cnt;
? ? cout<<"input the ori string"<<endl;
? ? cin>>ori_str;
? ? ori_len = ori_str.size();
? ? for (; pos < static_cast<int>(ori_len); ++pos)
? ? {
? ? ? ? tmp_A = ori_str[pos - 1];
? ? ? ? tmp_B = ori_str[pos];
? ? ? ? if (tmp_A != tmp_B && pos != static_cast<int>(ori_len-1))
? ? ? ? ///沒到末尾的時候,AB不同
? ? ? ? {
? ? ? ? ? ? if (cnt == 1)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? sht_str.push_back(tmp_A);
? ? ? ? ? ? }
? ? ? ? ? ? else
? ? ? ? ? ? {
? ? ? ? ? ? ? ? c_cnt = cnt + '0';
? ? ? ? ? ? ? ? sht_str.push_back(c_cnt);
? ? ? ? ? ? ? ? sht_str.push_back(tmp_A);
? ? ? ? ? ? ? ? cnt = 1;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? else if (tmp_A != tmp_B && pos == static_cast<int>(ori_len-1))
? ? ? ? ///在末尾,但是A,B不同
? ? ? ? {
? ? ? ? ? ? if (cnt == 1)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? sht_str.push_back(tmp_A);
? ? ? ? ? ? }
? ? ? ? ? ? else
? ? ? ? ? ? {
? ? ? ? ? ? ? ? sht_str.push_back(cnt);
? ? ? ? ? ? ? ? sht_str.push_back(tmp_A);
? ? ? ? ? ? ? ? cnt = 1;
? ? ? ? ? ? }
? ? ? ? ? ? sht_str.push_back(tmp_B);
? ? ? ? }
? ? ? ? else if (tmp_A == tmp_B && pos != static_cast<int>(ori_len-1))
? ? ? ? ///不在末尾,AB相同
? ? ? ? {
? ? ? ? ? ? ++cnt;
? ? ? ? }
? ? ? ? else if (tmp_A == tmp_B && pos == static_cast<int>(ori_len-1))
? ? ? ? ///在末尾,AB相同
? ? ? ? {
? ? ? ? ? ? cnt++;
? ? ? ? ? ? c_cnt = cnt + '0';
? ? ? ? ? ? sht_str.push_back(c_cnt);
? ? ? ? ? ? sht_str.push_back(tmp_A);
? ? ? ? }
? ? }
? ? cout<<sht_str;
? ? return 0;
}
總結
以上是生活随笔為你收集整理的字符串压缩之C++实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux安装jdk配置环境变量无效(不
- 下一篇: b站python_B站最受欢迎的Pyth