您的位置:首页 > 其它

《Cracking the Coding Interview》——第1章:数组和字符串——题目5

2014-03-18 01:44 387 查看
2014-03-18 01:40

题目:对字符串进行类似游程编码的压缩,如果压缩完了长度更长,则返回不压缩的结果。比如:aabcccccaaa->a2b1c5a3,abc->abc。

解法:Count and say.

代码:

// 1.5 Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2b1c5a3. If the compressed string  wouldn't become smaller than the original string, your method should return the original string.
#include <iostream>
#include <string>
using namespace std;

class Solution {
public:
string compressString(const string str) {
string res = "";

int i, j;
int len = (int)str.length();
char tmp[50];

i = 0;
while (i < len) {
j = i + 1;
while (j < len && str[i] == str[j]) {
++j;
}
sprintf(tmp, "%c%d", str[i], j - i);
res = res + string(tmp);
i = j;
}

if (res.length() < str.length()) {
return res;
} else {
return str;
}
}
};

int main()
{
string str;
Solution sol;

while (cin >> str) {
cout << sol.compressString(str) << endl;
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐