您的位置:首页 > 其它

CareerCup 1.5

2013-03-22 11:50 429 查看
1.5 Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaa would become a2b1c5a3. If the "compressed" string would not become smaller than the original string, your method should
return the original string.

string toString(int n) {
stringstream ss;
ss << n;
return ss.str();
}

string compress(string str) {
char c;
int cnt = 0;
string newStr;

for (int i = 0; i < str.length(); i++) {
if (str[i] != c) {
if (cnt > 0) {
newStr += c;
newStr += toString(cnt);
}
c = str[i];
cnt = 1;
} else {
cnt++;
}
}
newStr += c;
newStr += toString(cnt);

if (newStr.length() < str.length())
return newStr;
else
return str;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: