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;}



0 0
原创粉丝点击