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

    题目描述:

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

    分析:

    如果从前往后替换空格,那么每遇到一个空格就需要将还没遍历到的字符后移,总的移动步数将会很多。

    所以我们考虑先求出替换空格之后的字符串的长度,再从后往前遍历进行替换,将会大大减少替换的次数,也不会覆盖还没遍历的字符。

    代码:

     1 class Solution {
     2 public:
     3     void replaceSpace(char *str, int length) {
     4         int oldLength = strlen(str);    // 没替换前的字符串长度
     5         int newLength = oldLength;
     6         for(int i = 0; i < oldLength; i++) {  // 求出替换空格后的字符串长度
     7             if(str[i] == ' ')
     8                 newLength += 2;
     9         }
    10         if(newLength > length) return;  // 新长度超过限制的最长长度,则无法替换
    11         while(oldLength >= 0 && newLength > oldLength) {    // 从后往前替换空格
    12             if(str[oldLength] == ' ') {
    13                 str[newLength--] = '0';
    14                 str[newLength--] = '2';
    15                 str[newLength--] = '%';
    16                 oldLength--;
    17             } else {
    18                 str[newLength--] = str[oldLength--];
    19             }
    20         }
    21     }
    22 };
  • 相关阅读:
    顺序表的扩容
    顺序表的插入
    顺序表的构造
    C# ContentType: "application/json" 请求方式传json
    顺序表构造,插入,扩容操作
    顺序表
    线性表
    算法
    数据结构的分类
    什么是数据结构
  • 原文地址:https://www.cnblogs.com/jacen789/p/7737499.html
Copyright © 2011-2022 走看看