題目描述
利用字符重複出現的次數,編寫一個方法,實現基本的字符串壓縮功能。比如,字符串“aabcccccaaa”經壓縮會變成“a2b1c5a3”。若壓縮後的字符串沒有變短,則返回原先的字符串。
給定一個string iniString爲待壓縮的串(長度小於等於3000),保證串內字符均由大小寫英文字母組成,返回一個string,爲所求的壓縮後或未變化的串。
返回:"a2b1c5a3"
"welcometonowcoderrrrr"
返回:"welcometonowcoderrrrr"
首先,感謝大神指點,指出了我代碼中數量大於個位數時候,索引出現的問題。
先說我初始解法主要問題:1. 修改string中的值(replace,insert,erase); 2. 修改之後對於index的調整;3. 結尾時的特殊情況考慮。
附代碼:
#include <iostream>
#include <string>
#include <sstream>
#include <stdio.h>
using namespace std;
int main()
{
string s("aabcccccccaaa");
int num = 0;
char a = ' ';
int len = s.length();
for (int i = 0, times = 0;;)
{
stringstream n;
times++;
if (times == len)
{
if (a == s[i])
{
num++;
n << num;
s.replace(i - num + 2, num - 1, n.str());
}
else
{
n << num;
s.replace(i - num + 1, num - 1, n.str());
s += "1";
}
break;
}
else
{
if (a == s[i])
{
num++;
i++;
}
else
{
if (num != 0)
{
n << num;
s.replace(i - num + 1, num - 1, n.str());
i -= num - 2;
}
num = 1;
a = s[i];
i++;
}
}
}
cout << s << endl;
system("pause");
return 0;
}
然後說大神的思路,不要在原string裏做修改,直接新建一個string,醍醐灌頂。
class Zipper {
public:
string zipString(string iniString) {
// write code here
string snew("");
char a = ' ';
int num = 0;// 初始化有點問題
for (int i = 0; i < iniString.length(); i++)
{
stringstream n;
if (i == iniString.length() - 1)
{
if (iniString[i] == a)// 說明不是第一個
{
num++;
n << num;
snew += n.str();
}
else// 說明最後一個是新的元素
{
n << num;
snew += n.str() + iniString[i] + "1";
}
}
else
{
if (iniString[i] == a)
num++;
else
{
n << num;
if (num != 0)
snew += n.str() + iniString[i];
else
snew += iniString[i];
num = 1;
a = iniString[i];
}
}
}
if (snew.length() < iniString.length())
return snew;
else
return iniString;
}
};