剑指offer第四题:替换空格

思路应该使用指针从后向前替换字符串。不过python用不到。

class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        new_s=''
        for j in s:
            if j==' ':
                new_s=new_s+'%20'
            else:
                new_s=new_s+j
        return new_s        

特别的,if==' '。是因为python不允许在if语句的条件中赋值。所以if 1=2 会报错(https://zhidao.baidu.com/question/462174743.html)。

还可以使用replace函数

class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        return s.replace(' ','%20')

不过算是赖皮。



最后c++方法(从左至右遍历,从右至左替换)

链接:https://www.nowcoder.com/questionTerminal/4060ac7e3e404ad1a894ef3e17650423
来源:牛客网

//思路
//1:从前往后插入,这样移动·的次数多不建议
//2:从后往前插入

class Solution {
public:
void replaceSpace(char *str,int length) {
        //遍历一边字符串找出空格的数量
        if(str==NULL||length<0)
            return ;
        int i=0;
        int oldnumber=0;//记录以前的长度
        int replacenumber=0;//记录空格的数量
        while(str[i]!='\0')
            {
               oldnumber++;
               if(str[i]==' ')
                   {
                     replacenumber++;
                   }
                  i++; 
            }
        int newlength=oldnumber+replacenumber*2;//插入后的长度
        if(newlength>length)//如果计算后的长度大于总长度就无法插入
            return ;
        int pOldlength=oldnumber; //注意不要减一因为隐藏个‘\0’也要算里
        int pNewlength=newlength;
        while(pOldlength>=0&&pNewlength>pOldlength)//放字符
            {
              if(str[pOldlength]==' ') //碰到空格就替换
                  {
                     str[pNewlength--]='0';
                     str[pNewlength--]='2';
                     str[pNewlength--]='%';
                     
                  }
               else //不是空格就把pOldlength指向的字符装入pNewlength指向的位置
               {
                    str[pNewlength--]=str[pOldlength];
                   
               }
             pOldlength--; //不管是if还是elsr都要把pOldlength前移
             
           }
        

}
};

猜你喜欢

转载自blog.csdn.net/zhangjiaxuu/article/details/80738267