美文网首页每天写1000字
跟我一起学算法系列4---替换空格

跟我一起学算法系列4---替换空格

作者: 充电实践 | 来源:发表于2017-11-07 23:22 被阅读0次

    1.题目描述

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

    2.算法分析

    java实现该功能可以直接使用replace类函数,然而我们从算法的角度分析,可以先遍历统计出字符串中空格的个数,假设为n,替换空格之后的字符串长度在原有长度的基础上增加了2n。因此新的字符串长度确定了,从后向前遍历原字符串,遇到空格就将相应字符替换为%20,不是空格的原样复制。

    3.代码实例

      public String replaceSpace(StringBuffer str)
      {
        if(null == str)
        {
            return "";
        }
    
        int len = str.length();
        int count = 0;
        
        for (int i = 0; i < len; i++) {
            if(str.charAt(i) == ' ')
            {
                count++;
            }
        }
        
        int newLen = len + 2*count;
        int index = newLen - 1;
        char[] newChar = new char[newLen];
        
        while(len > 0)
        {
            if(str.charAt(len - 1) == ' ')
            {
                newChar[index--] = '0';
                newChar[index--] = '2';
                newChar[index--] = '%';
            }
            else
            {
                newChar[index--] = str.charAt(len - 1);
            }
            
            len--;
        }
        
        return String.valueOf(newChar);
    }
    

    相关文章

      网友评论

        本文标题:跟我一起学算法系列4---替换空格

        本文链接:https://www.haomeiwen.com/subject/lovsmxtx.html