212 空格替换

原题网址:https://www.lintcode.com/problem/space-replacement/description

描述

设计一种方法,将一个字符串中的所有空格替换成 %20 。你可以假设该字符串有足够的空间来加入新的字符,且你得到的是“真实的”字符长度。

你的程序还需要返回被替换后的字符串的长度。

如果使用 Java 或 Python, 程序中请用字符数组表示字符串。

您在真实的面试中是否遇到过这个题?  

样例

对于字符串"Mr John Smith", 长度为 13

替换空格之后,参数中的字符串需要变为"Mr%20John%20Smith",并且把新长度 17 作为结果返回。

挑战

在原字符串(字符数组)中完成替换,不适用额外空间

标签
字符串处理
Cracking The Coding Interview
 
思路:while循环遍历字符串,如果遇到空格,将当前位置及之后的字符向后移动两位(新增两个空间),然后将字符‘%’,‘2’,‘0’ 插进来,更新end位置,当前索引 i 后移三位循环继续;如果不是空格,i++;最后return end+1。
 
AC代码:
class Solution {
public:
    /*
     * @param string: An array of Char
     * @param length: The true length of the string
     * @return: The true length of new string
     */
    int replaceBlank(char string[], int length) {
        // write your code here
    if (length==0)
     {
         return 0;
     }
     int end=length-1;
     int i=0;
     while(i!=end+1)
     {
         if (string[i]!=' ')
         {
             i++;
         }
         else 
         {
             for (int j=end;j>=i;j--)
             {
                 string[j+2]=string[j];
             }
             string[i]='%';
             string[i+1]='2';
             string[i+2]='0';
             i=i+3;
             end=end+2;
         }
     }

     return end+1;
    }
};

PS:一开始while循环的循环条件写成了 i != end,运行到 “helloworld ” 出错,尴尬……最后一个字符索引是end,所以循环条件应该是 i != end+1。

 
更高效的解法是统计空格数量,则新串长度为原来长度+2×空格数。然后从后向前遍历原串,遇到空格就替换,否则正常复制。
 

猜你喜欢

转载自www.cnblogs.com/Tang-tangt/p/9190642.html
212