• 剑指offer-替换空格


    题目描述

    请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
    时间限制:1秒 空间限制:32768K 热度指数:27315
     
    我的思路:将StringBuffer类型转换为String,然后使用replace方法(肤浅了,没有理解到题目要考察的知识点)
     1 class Solution {
     2     public String replaceSpace(StringBuffer str) {
     3         
     4         String string=str.toString();
     5         
     6         if(string!=null){
     7             string=string.replaceAll(" ", "%20");
     8         }        
     9         return string;   
    10         
    11     }
    12 }

    深入探究(replace方法的实现):

    以后补充

    优秀解法:

     1 链接:<a href="https://www.nowcoder.com/questionTerminal/4060ac7e3e404ad1a894ef3e17650423">https://www.nowcoder.com/questionTerminal/4060ac7e3e404ad1a894ef3e17650423</a>
     2 来源:牛客网
     3 
     4 //思路 
     5   //1:从前往后插入,这样移动·的次数多不建议 
     6   //2:从后往前插入 
     7 
     8   
     9 
    10   class Solution { 
    11   public: 
    12 
    13   void replaceSpace(char *str,int length) { 
    14           //遍历一边字符串找出空格的数量 
    15           if(str==NULL||length<0) 
    16               return ; 
    17           int i=0; 
    18           int oldnumber=0;//记录以前的长度 
    19           int replacenumber=0;//记录空格的数量 
    20           while(str[i]!='') 
    21               { 
    22                  oldnumber++; 
    23                  if(str[i]==' ') 
    24                      { 
    25                        replacenumber++; 
    26                      } 
    27                     i++28               } 
    29           int newlength=oldnumber+replacenumber*2;//插入后的长度 
    30           if(newlength>length)//如果计算后的长度大于总长度就无法插入 
    31               return ; 
    32           int pOldlength=oldnumber; //注意不要减一因为隐藏个‘’也要算里 
    33           int pNewlength=newlength; 
    34          
    35   while(pOldlength>=0&&pNewlength>pOldlength)//放字符 
    36               { 
    37                 if(str[pOldlength]==' ') //碰到空格就替换 
    38                     { 
    39                        str[pNewlength--]='0'; 
    40                        str[pNewlength--]='2'; 
    41                        str[pNewlength--]='%'; 
    42                         
    43                     } 
    44                  else //不是空格就把pOldlength指向的字符装入pNewlength指向的位置 
    45                  { 
    46                       str[pNewlength--]=str[pOldlength]; 
    47                       
    48                  } 
    49                pOldlength--; //不管是if还是elsr都要把pOldlength前移 
    50                 
    51              } 
    52            
    53 
    54   
    55 
    56 
    57   } 
    58   };
  • 相关阅读:
    [课程设计]Scrum 1.5 多鱼点餐系统开发进度(点餐页面框架修复及继续布置)
    [课程设计]Scrum 1.4 多鱼点餐系统开发进度(点餐页面框架布置)
    [课程设计]Scrum 1.3 多鱼点餐系统开发进度(系统主界面框架&美化)
    任务完成情况
    SCRUM项目4.0
    操作系统 实验三 进程调度模拟程序
    Scrum 项目3.0
    操作系统 实验二、作业调度模拟程序 【完整版】
    Scrum 项目2.0
    0428 《构建之法》第6~7章读后感
  • 原文地址:https://www.cnblogs.com/daneres/p/6512100.html
Copyright © 2020-2023  润新知