字符串壓縮

例如:aac  壓縮爲1ac


#include<iostream>

using namespace std;

int main()
{
	string str;
	cin >> str;
	char pre, now;
	int len = str.size();
	if (len <= 1)
	{
		cout << str;
		return 0;
	}
	pre = str[0];
	string ans="";
	int cnt =0;
	for (int i = 1; i < len; ++i)
	{
		now = str[i];
		if (now == pre)
		{
			cnt=cnt+1;
		}
		else
		{
			if (cnt == 0)
				ans = ans + pre;
			else
			{
				ans = ans + to_string(cnt) + pre;
				cnt = 0;
			}		
		}	
		   pre = now;
	}


	if((pre==now)&&(cnt!=0))
		ans = ans + to_string(cnt) + pre;
	else if(pre == now)
		ans = ans  + pre;
	cout << ans;
	return 0;


//  xyzzxy
	
	

}

 

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