剑指offer----005(字符串空格替换)
2018-01-19 14:24
405 查看
更多题目请点链接:《剑指offer》目录索引
问题描述:
实现一个函数,将字符串中的每个空格替换成%20。例如:”We are
hanppy.“,则输出“We%20are%20happy.”,要求时间复杂度为O(n)
问题分析:
根据描述,此题意思改变字符串内容,并且改变了原字符串长度;
要求时间复杂度为0(n),故不能直接替换;
思路:
第一步,求空格数:要知道改变字符串后的长度,需知道原字符串中空格数,才能确定替换后的字符串长度;
第二步,替换空格:将空格替换成字符串”%20”,替换时,从后往前遍历,遇到空格进行替换,这样做的好处是,可保证原字符串的完整性,不会覆盖原来的字符串(如图)
具体代码:
测试用例:
问题描述:
实现一个函数,将字符串中的每个空格替换成%20。例如:”We are
hanppy.“,则输出“We%20are%20happy.”,要求时间复杂度为O(n)
问题分析:
根据描述,此题意思改变字符串内容,并且改变了原字符串长度;
要求时间复杂度为0(n),故不能直接替换;
思路:
第一步,求空格数:要知道改变字符串后的长度,需知道原字符串中空格数,才能确定替换后的字符串长度;
第二步,替换空格:将空格替换成字符串”%20”,替换时,从后往前遍历,遇到空格进行替换,这样做的好处是,可保证原字符串的完整性,不会覆盖原来的字符串(如图)
具体代码:
void StringReplace(char* dst, int len) { assert(dst); assert(len>0); int count = 0, i = 0; while (dst[i] != '\0') { if (dst[i] == ' ') { ++count; } ++i; } int index = length ;//原字符串的尾 int newindex = length + count * 2;//新字符串的长度 if (newindex < length) { return; } while (index>=0 && newindex>=0) { if (dst[index] != ' ') { dst[newindex--] = dst[index]; } else { dst[newindex--] = '0'; dst[newindex--] = '2'; dst[newindex--] = '%'; } index--; } }
测试用例:
void Test() { char arr[30] = "We are happy."; int len = strlen(arr); printf("%s\n", arr); StringReplace(arr, len); printf("%s\n",arr); }
相关文章推荐
- 剑指offer 1,输入一个字符串,将字符串的空格替换成%20
- 【剑指offer】替换字符串中的空格
- 剑指offer——题目描述 请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
- 剑指offer 04_替换字符串中的空格
- java 剑指offer 第二题:请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
- 剑指offer - 将字符串中空格替换为20%
- java 剑指offer 第二题:请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
- 【剑指offer】实现一个函数来替换字符串中的空格
- C++笔试题(剑指offer 面试题4 替换字符串中的空格)
- 剑指offer-04:字符串替换空格
- 【剑指offer】替换字符串中的空格_04
- 【剑指offer】请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
- 【剑指offer】替换字符串中的空格
- 【剑指offer】2.3.2 字符串——面试题4:替换空格
- 剑指Offer——字符串空格替换
- 剑指offer——字符串替换空格
- 剑指offer 替换字符串中的空格
- 【剑指offer】将字符串中的空格替换成"%20"
- 剑指Offer-5:替换字符串的空格
- 【剑指offer】将空格替换制定字符串