《Cracking the Coding Interview》——第1章:数组和字符串——题目5
2014-03-18 01:44
387 查看
2014-03-18 01:40
题目:对字符串进行类似游程编码的压缩,如果压缩完了长度更长,则返回不压缩的结果。比如:aabcccccaaa->a2b1c5a3,abc->abc。
解法:Count and say.
代码:
题目:对字符串进行类似游程编码的压缩,如果压缩完了长度更长,则返回不压缩的结果。比如: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; }
相关文章推荐
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目2
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目3
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目4
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目6
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目7
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目8
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目1
- 《Cracking the Coding Interview》——第7章:数学和概率论——题目1
- 《Cracking the Coding Interview》——第9章:递归和动态规划——题目8
- 《Cracking the Coding Interview》——第11章:排序和搜索——题目7
- 《Cracking the Coding Interview》——第14章:Java——题目6
- 《Cracking the Coding Interview》——第17章:普通题——题目1
- 《Cracking the Coding Interview》——第17章:普通题——题目7
- 《Cracking the Coding Interview》——第17章:普通题——题目14
- Cracking the Coding Interview 题目分析笔记—— Array and String
- 《Cracking the Coding Interview》——第3章:栈和队列——题目6
- 《Cracking the Coding Interview》——第5章:位操作——题目4
- crack the coding interview 数组与字符串 1.5
- 《Cracking the Coding Interview》——第9章:递归和动态规划——题目9
- 《Cracking the Coding Interview》——第11章:排序和搜索——题目2