题目描述
- 请实现一个函数,把字符串中的每个空格替换成"%20"。例如输入“We are happy.”,则输出“We%20are%20happy.”。
算法分析
- 在同一个字符串中操作,判断空格个数,修改字符串空间,逆向添加字符,遇到空格替换为%20
提交代码:
class Solution { public: void replaceSpace(char *str, int length) { if (!str) return; int blankNumber = 0; int originLength = 0; while (str[originLength] != '\0') { if (str[originLength] == ' ') ++blankNumber; ++originLength; } int newLength = originLength + 2 * blankNumber; if (newLength > length) return; int i = originLength; int j = newLength; while (i >= 0 && j >= 0) { if (str[i] != ' ') str[j--] = str[i]; else { str[j--] = '0'; str[j--] = '2'; str[j--] = '%'; } --i; } } };
测试代码:
#include<iostream> #include<vector> using namespace std; /* // 面试题5: 请实现一个函数,将一个字符串中的空格替换成“%20”。 例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。 */ // ====================测试代码==================== void Test(char* testName, char str[], int length, char expected[]) { Solution s; if (testName != nullptr) printf("%s begins: ", testName); s.replaceSpace(str, length); if (expected == nullptr && str == nullptr) printf("passed.\n"); else if (expected == nullptr && str != nullptr) printf("failed.\n"); else if (strcmp(str, expected) == 0) printf("passed.\n"); else printf("failed.\n"); } // 空格在句子中间 void Test1() { const int length = 100; char str[length] = "hello world"; Test("Test1", str, length, "hello%20world"); } // 空格在句子开头 void Test2() { const int length = 100; char str[length] = " helloworld"; Test("Test2", str, length, "%20helloworld"); } // 空格在句子末尾 void Test3() { const int length = 100; char str[length] = "helloworld "; Test("Test3", str, length, "helloworld%20"); } // 连续有两个空格 void Test4() { const int length = 100; char str[length] = "hello world"; Test("Test4", str, length, "hello%20%20world"); } // 传入nullptr void Test5() { Test("Test5", nullptr, 0, nullptr); } // 传入内容为空的字符串 void Test6() { const int length = 100; char str[length] = ""; Test("Test6", str, length, ""); } //传入内容为一个空格的字符串 void Test7() { const int length = 100; char str[length] = " "; Test("Test7", str, length, "%20"); } // 传入的字符串没有空格 void Test8() { const int length = 100; char str[length] = "helloworld"; Test("Test8", str, length, "helloworld"); } // 传入的字符串全是空格 void Test9() { const int length = 100; char str[length] = " "; Test("Test9", str, length, "%20%20%20"); } int main(int argc, char* argv[]) { Test1(); Test2(); Test3(); Test4(); Test5(); Test6(); Test7(); Test8(); Test9(); return 0; }