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.
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; }
相关文章推荐
- CareerCup1.5
- CareerCup_1_7
- Sorting_Searching 读入数字流求rank @CareerCup
- Moderate BST转双向链表 @CareerCup
- CareerCup the maximum longest continous sequence of 0s
- CareerCup Finds all the elements that appear more than n/3 times in the list
- LinkLists 删除链表中的一个给定指针的结点 @CareerCup
- Stack_Queue 汉诺塔Hanoi问题 @CareerCup
- CareerCup Given an array of (unsorted) integers, arrange them such that a < b > c < d > e... etc.
- CareerCup Given a binary matrix of N X N of integers , you need to return only unique rows of binary
- CareerCup How would you implement a secondary sorting
- CareerCup 17中等难题 Q17.3 阶乘尾随零个数
- 《Career Cup Top 150 Questions and Answers》阅读笔记
- Moderate Swap不用临时变量 @CareerCup
- CareerCup Arrange the 2 x 1 boards on the 2 x n board
- LinkLists 把一个链表根据一个值分成两半 @CareerCup
- Stack_Queue 两个栈实现一个队列 @CareerCup
- CareerCup perform increment operation on ai = ai+1 and decrements operation on aj = aj - 1
- CareerCup Given an array A[], find (i, j) such that A[i] < A[j] and (j - i) is maximum.
- CareerCup Round-robin tournament