《Cracking the Coding Interview》——第1章:数组和字符串——题目4
2014-03-18 01:40
423 查看
2014-03-18 01:36
题目:给定一个字符串,将其中的空格‘ ’替换为‘%20’,你可以认为字符串尾部有足够空间来容纳新增字符。请不要额外开辟数组完成。
解法:先从前往后统计空格个数,然后从后往前填充字符,以免其他无关字符被‘%20’覆盖掉。
代码:
题目:给定一个字符串,将其中的空格‘ ’替换为‘%20’,你可以认为字符串尾部有足够空间来容纳新增字符。请不要额外开辟数组完成。
解法:先从前往后统计空格个数,然后从后往前填充字符,以免其他无关字符被‘%20’覆盖掉。
代码:
// 1.4 Write a method to replace all spaces in a string with '%20'. // do it in-place and backward. #include <cstdio> #include <cstring> using namespace std; class Solution { public: void replaceSpace(char *str) { if (nullptr == str) { return; } int i, j; int len = (int)strlen(str); int cc = 0; for (i = 0; i < len; ++i) { if (str[i] == ' ') { ++cc; } } int tc = 0; for (i = len - 1; i >= 0; --i) { if (str[i] == ' ') { ++tc; } else { break; } } cc -= tc; j = i; i = cc; while (j >= 0) { if (str[j] == ' ') { --cc; str[j + 2 * cc] = '%'; str[j + 2 * cc + 1] = '2'; str[j + 2 * cc + 2] = '0'; } else { str[j + 2 * cc] = str[j]; } --j; } if (2 * i > tc) { str[len - tc + 2 * i] = 0; } } }; int main() { char str[1000]; Solution sol; while (gets(str) != nullptr) { sol.replaceSpace(str); puts(str); } return 0; }
相关文章推荐
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目2
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目3
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目5
- 《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