剑指offer05

剑指offer05:替换空格

题目描述

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

解法一:判断空格,后移两位元素

class Solution {
public:
    void replaceSpace(char *str, int length) {
        for (int i = 0; i<length; i++)
        {
            if (str[i] == ' ') //如果存在空格
            {
                for (int j = length + 1; j >= i + 3; j--)  //后面的 元素向后移动两位
                    str[j] = str[j - 2];
                str[i] = '%';
                str[i + 1] = '2';
                str[i + 2] = '0';
                length += 2;
            }
        }
    }
};

解法二:利用string和find函数

class Solution2 {
public:
    void replaceSpace(char *str, int length) {
        string s(str);
        int i = 0;
        while ((i = s.find(' ', i))>-1) {
            s.erase(i, 1);
            s.insert(i, "%20");

        }
        auto ret = s.c_str();
        strcpy(str, ret);
    }
};

main函数

#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <ctype.h>
#include <cctype>
using namespace std;

int main()
{
    char s[18] = "I love you!";
    Solution a;
    a.replaceSpace(s, 18);
    for (int i = 0; i < 18; i++)
        cout << s[i];

    system("pause");
    return 0;
}

   转载规则


《剑指offer05》 赵小亮 采用 知识共享署名 4.0 国际许可协议 进行许可。
 上一篇
剑指offer07 剑指offer07
剑指offer07:斐波那契数列 题目描述大家都知道斐波那契数列,现在要求输入一个整数n, 请你输出斐波那契数列的第n项(从0开始,第0项为0,第1项是1)。 n<=39 解法一:基于for循环和双标记class Solution
2020-05-05
下一篇 
Leetcode485 Leetcode485
Leetcode485:最大连续1的个数 题目描述示例 1: 输入: [1,1,0,1,1,1] 输出: 3 解释: 开头的两位和最后的三位都是连续1,所以最大连续1的个数是 3. 注意: 输入的数组只包含 0 和1。 输入数组的长度
2020-04-26
  目录