zoukankan      html  css  js  c++  java
  • 2、剑指offer--替换空格

    题目描述

    请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
     
    解题思路:遍历一遍求出空格个数,继而求出变换完的字符串的长度;然后从后向前赋值进行替换。
     
     1 class Solution {
     2 public:
     3     void replaceSpace(char *str,int length) {
     4        //先确定替换后的字符串的长度,然后从后往前替换
     5        if(str == NULL || length <= 0)
     6             return;
     7         int totalLength = 0;
     8         int blankLength = 0;
     9         for(int i=0;i<length;i++)
    10         {
    11             if(str[i] == ' ')
    12             {
    13                 blankLength++;
    14             }
    15         }
    16         totalLength = length + 2*blankLength;
    17         while(length>=0 && totalLength>length)
    18         {
    19             if(str[length-1] == ' ')
    20             {
    21                 str[--totalLength] = '0';
    22                 str[--totalLength] = '2';
    23                 str[--totalLength] = '%';
    24             }
    25             else
    26             {
    27                 str[--totalLength] = str[length-1];
    28             }
    29             length--;
    30         }
    31     }
    32 };
  • 相关阅读:
    ebs R12 支持IE11
    reloc: Permission denied
    3.23考试小记
    3.21考试小记
    3.20考试小记
    3.17考试小记
    3.15考试小记
    3.13考试小记
    3.12考试小记
    3.10考试小记
  • 原文地址:https://www.cnblogs.com/qqky/p/6768992.html
Copyright © 2011-2022 走看看