zoukankan      html  css  js  c++  java
  • 剑指offer-4.字符串替换

    0 题目

    实现一个函数,将字符串中的 空格 替换为“%20”

    1 分析

    采用常规的从前向后的方式,那么后面的将移动很多次。

    如果先计算出替换后字符串的总长度,然后从后向前开始替换,会效率很多。

    void replaceSpace(char *str, int length)
    {
        
        int counts = 0;
        char *str_tmp = str;
        if (str == nullptr)
        {
            return;
        }
        
        // 计算需要替换的字符个数
        while (*str_tmp != '')
        {
            if (*str_tmp == ' ')
            {
                ++counts;
            }
            ++str_tmp;
        }
    
        // 这里将空格替换为 %20,因此一个空格需要额外的两个空间来存储,因此每个空格扩容2个。
        int index_new = length + counts * 2 - 1; // 新的尾下标
        int index = length - 1; // 旧的
    
        while (index >= 0)
        {
            if (str[index] == ' ') //需要替换的时候替换
            {
                str[index_new--] = '0';
                str[index_new--] = '2';
                str[index_new--] = '%';
            }
            else
            {
                str[index_new--] = str[index];//不需要替换的时候直接赋值
            }
            --index; // 向前移动
        }
    }
    

      

  • 相关阅读:
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
  • 原文地址:https://www.cnblogs.com/perfy576/p/8568719.html
Copyright © 2011-2022 走看看