面试题5:替换空格

来源:互联网 发布:模具设计与制造软件 编辑:程序博客网 时间:2024/06/06 07:48
题目:

请实现一个函数,把字符串中的每个空格替换成"%20"。

解答:

可以先统计空格数,然后扩大字符串的size,然后从后面开始往前移动或添加字符到对应位置,用两个指针实现。

时间复杂度:O(n)

空间复杂度:O(1)

#include <iostream>#include <vector>#include <string>using namespace std;void replace(string &str){int count = 0;char *ptr = &str[0];while (*ptr != '\0'){if (*ptr == ' ') count+=2;++ptr;}for (int i = 0; i < count; ++i)str += " ";--ptr;char *lastPtr = ptr+count;while (ptr >= &str[0]){if (*ptr != ' '){*lastPtr = *ptr;--ptr;--lastPtr;}else{--ptr;*(lastPtr--) = '0';*(lastPtr--) = '2';*(lastPtr--) = '%';}}}int main(){string str(" we are family hello ");replace(str);cout << str << endl;return 0;}


0 0
原创粉丝点击