遊程編碼

/*
問題描述:遊程編解碼,給定一個字符串"aaasssdd",編碼爲"3a3c2d", 解碼爲給定一個字符串"3d2s",解碼爲"dddss"
來源:網易算法課
日期:2017-10-24
*/
#include <iostream>
#include <string>
using namespace std;

class RLE{
public:
	string encode(string s)
	{
		string str = "";
		char last = s[0];
		int count = 0;

		for (int i = 0; i < s.length(); i++)
		{
			if (s[i] == last)
			{
				count++;
			}
			else
			{
				str += to_string(count);
				str += last;
				count = 1;
				last = s[i];
			}
		}

		str += to_string(count);
		str += last;

		return str;
	}

	string decode(string s)
	{
		string str = "";
		for (int i = 0; i < s.length(); i += 2)
		{
			int count = s[i] - '0';
			char c = s[i + 1];

			for (int j = 0; j < count; j++)
				str += c;
		}
		return str;
	}
};

/*
int main()
{
	string str = "aaaddc";
	RLE rle;
	string s = rle.encode(str);
	cout << s << endl;
	cout << rle.decode(s) << endl;

	return 0;
}
*/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章