剑指offer——面试题5:替换空格
Posted acm-jing
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了剑指offer——面试题5:替换空格相关的知识,希望对你有一定的参考价值。
利用STL:
1 #include"iostream" 2 #include"stdio.h" 3 #include"algorithm" 4 using namespace std; 5 6 string ReplaceBlank(string src) 7 { 8 if(src.find(" ")>src.length()) 9 return src; 10 while(src.find(" ")<src.length()) 11 { 12 int pos=src.find(" "); 13 src=src.replace(pos,1,"%20"); 14 } 15 return src; 16 } 17 18 void Test(char *testName,string testStr,string resStr) 19 { 20 if(testName!=nullptr) 21 printf("the %s begin:",testName); 22 if(testStr=="") 23 { 24 printf("the source string is null! "); 25 return; 26 } 27 string res=ReplaceBlank(testStr); 28 if(res==resStr) 29 printf("passed. "); 30 else 31 printf("failed "); 32 } 33 34 //包含空格的字符串 35 void Test1() 36 { 37 Test("Test1","We are happy enough !","We%20are%20happy%20enough%20!"); 38 } 39 40 //不包含空格的字符串 41 void Test2() 42 { 43 Test("Test2","WeAreHappy","WeAreHappy"); 44 } 45 46 //空字符串 47 void Test3() 48 { 49 Test("Test3","",""); 50 } 51 52 int main() 53 { 54 Test1(); 55 Test2(); 56 Test3(); 57 return 0; 58 }
官方给出的O(n)复杂度的算法:
1 // 面试题5:替换空格 2 // 题目:请实现一个函数,把字符串中的每个空格替换成"%20"。例如输入“We are happy.”, 3 // 则输出“We%20are%20happy.”。 4 5 #include <cstdio> 6 #include <cstring> 7 8 /*length 为字符数组str的总容量,大于或等于字符串str的实际长度*/ 9 void ReplaceBlank(char str[], int length) 10 { 11 if(str == nullptr && length <= 0) 12 return; 13 14 /*originalLength 为字符串str的实际长度*/ 15 int originalLength = 0; 16 int numberOfBlank = 0; 17 int i = 0; 18 while(str[i] != ‘