Cracking The Coding Interview 3rd -- 1.4
来源:互联网 发布:免税店mac多少钱 编辑:程序博客网 时间:2024/05/17 06:17
Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end of the string to hold the additional characters, and that you are given the "true" length of the string. (Note: if implementing in Java, please use a character array so that you can perform this operation in place).
Solution: A common approach in string manipulation problems is to edit the string starting from the end and work backwards. For this problem, we work through two scan approach. In the first scan, we count how many spaces there are in the string. This is used to compute how long the final string should be. In the second pass, which is done in reverse order, we actually edit the string.
Header file
#ifndef __QUESTION_1_4_H_CHONG__#define __QUESTION_1_4_H_CHONG__class Question1_4 {public: void replaceSpaces(char str[], int length); int run();};#endif // __QUESTION_1_4_H_CHONG__
Source file
#include "stdafx.h"#include <iostream>#include "Question1_4.h"using namespace std;void Question1_4::replaceSpaces(char str[], int length) { int numOfSpaces = 0; for (int i=0; i<length; i++) { if (str[i]==' ') { numOfSpaces++; } } int trueLength = length + 2*numOfSpaces; for (int i=length-1, j=trueLength-1; i>=0; i--, j--) { if (str[i]!=' ') { str[j] = str[i]; } else { str[j-2] = '%'; str[j-1] = '2'; str[j] = '0'; j = j - 2; } }}int Question1_4::run() { char str[100] = "Hello Chong!"; int length = 12; replaceSpaces(str, length); cout << str << endl; return 0;}
- Cracking The Coding Interview 3rd -- 1.4
- Cracking The Coding Interview 3rd -- 00
- Cracking The Coding Interview 3rd -- 1.1*
- Cracking The Coding Interview 3rd -- 1.2
- Cracking The Coding Interview 3rd -- 1.3
- Cracking The Coding Interview 3rd -- 1.5*
- Cracking The Coding Interview 1.4
- Cracking the Coding Interview
- 《Cracking the coding interview》
- Cracking The Coding Interview
- Cracking the coding interview
- Cracking the coding interview
- Cracking the coding interview--Q9.3
- Cracking the Coding Interview Chap1 Q1.3
- Cracking the coding interview--Q1.3
- Cracking the coding interview--Q2.3
- Cracking the coding interview--Q3.3
- Cracking the coding interview--Q1.3
- 黑马程序员学习log第九篇基础知识:JAVA的面向对象之正则表达式及反射总结
- 断点续传
- 图,谱,马尔可夫过程,聚类结构
- [转]Linux 下批量修改文件名
- 进程上下文和中断上下文
- Cracking The Coding Interview 3rd -- 1.4
- 整理:分页存储过程整理
- 献母校
- 黑马程序员_值类型和引用类型
- 黑马程序员学习log第十篇基础加强总结
- 马尔科夫链算法
- 黑马程序_网络编程
- 日语学习之一
- 关于flash跨域问题的解决办法