zoukankan      html  css  js  c++  java
  • [剑指Offer] 替换空格

    问题描述

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

    分析

    乍一看不就一个replace解决问题,的确这样是能AC的

    如下面这个C#版的,一行就能解决

    public string replaceSpace(string str)
    {
        return str.Replace(" ", "%20");
    }
    

    如果不用自带的replace偷懒,有两种思路:

    1. 创建新的字符串
    2. 原地replace

    创建新字符串

    这种方法比较简单,空间换时间,时间复杂度(O(n)),空间复杂度(O(n))

    public String replaceSpace(StringBuffer str) {
        String result = "";
        int len = str.length();
        for (int i = 0; i < len; i++) {
            if (str.charAt(i) == ' ') { result += "%20";}
            else {result += str.charAt(i);}
        }
    
        return result;
    }
    

    原地replace

    以C++为例,原地replace要考虑到String的储存方式,是存在一块连续的内存里,空格可能出现在字符串的中间位置,要替换成%20需要将空格后的元素向后移动腾出位置

    1. 统计空格的数量emptyCount(一次for循环)
    2. 计算元素向后移动的偏移量offset

    每多一个空格,元素就要多向后移动2位,当一个空格被%20填充后,需要后移的位数就减少2

    offset = (emptyCount - tmpCount) * 2

    ' '%20

    void replaceSpace(char *str,int length) {
        int emptyCount = 0, tmpCount = 0;
        for(int i = 0; i < length; ++i) {
            if (str[i] == ' ') {
                ++emptyCount;
            }
        }
    
        for (int j = length - 1; j >= 0; --j) {
            if (str[j] == ' ') {
                str[j+(emptyCount - tmpCount)*2] = '0';
                str[j+(emptyCount - tmpCount)*2-1] = '2';
                str[j+(emptyCount - tmpCount)*2-2] = '%';
                ++tmpCount;
                continue;
            }
            str[j+(emptyCount - tmpCount) * 2] = str[j];
        }
    }
    
  • 相关阅读:
    当期所得税费用总额
    所得税净利润算法
    [AGC028B]Removing Blocks 概率与期望
    bzoj 4319: cerc2008 Suffix reconstruction 贪心
    bzoj 2430: [Poi2003]Chocolate 贪心
    BZOJ 2839: 集合计数 广义容斥
    luogu 5505 [JSOI2011]分特产 广义容斥
    CF504E Misha and LCP on Tree 后缀自动机+树链剖分+倍增
    CF798D Mike and distribution 贪心
    CF707D Persistent Bookcase 可持久化线段树
  • 原文地址:https://www.cnblogs.com/arcsinw/p/12943365.html
Copyright © 2011-2022 走看看