2.替换空格(做第二遍时感觉仍有有难度,第三次做就没有难度了)

来源:互联网 发布:prizegiving软件 编辑:程序博客网 时间:2024/05/16 01:52

题目描述

请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

<pre name="code" class="cpp">class Solution {public:void replaceSpace(char *str,int length) {        if ( !str || length <= 0 ) return ;                int sumOfLetter = 0 ;        int sumOfBlank = 0 ;       char* pStr = str ;                while ( *pStr != '\0' ) {            if ( *pStr != ' ' )                sumOfLetter ++ ;            else                sumOfBlank ++ ;            pStr ++ ;        }                int orgLength = sumOfLetter + sumOfBlank ;        int newLength = sumOfLetter + sumOfBlank * 2 ;                char* pNewStr = pStr + ( 2 * sumOfBlank ) ;                while ( pStr >= str ) {            if ( *pStr != ' ' ) {                *pNewStr = *pStr ;                pStr -- ;                pNewStr -- ;            } else {                *pNewStr-- = '0' ;                *pNewStr-- = '2' ;                *pNewStr-- = '%' ;                *pStr-- ;            }        }}};


做第二遍的感悟:

字符串以'\0'作为结束,'\0'也是字符串的一部分

        while ( *pStr != '\0' ) {            if ( *pStr != ' ' )                sumOfLetter ++ ;            else                sumOfBlank ++ ;            pStr ++ ;        }
这个while循环做完后,pStr指向的是str字符串的'\0'位置

第三次做:

//length为牛客系统规定字符串输出的最大长度,固定为一个常数class Solution {public:void replaceSpace(char *str, int length) {if (str == NULL) return ;int orgLength = length ;int blank = 0 ;char* pStr = str ;while (*pStr != '\0') {if (*pStr == ' ') blank++ ;++pStr ;}char* pOld = pStr ;char* pNew = pStr + 2 * blank ;while (pOld >= str) {if (*pOld == ' ') {*pNew-- = '0' ;*pNew-- = '2' ;*pNew-- = '%' ;--pOld ;}else {*pNew = *pOld ;pNew-- ;pOld-- ;}}str = pNew ;}};


0 0
原创粉丝点击