剑指offer-2 《替换空格》

题目描述:(数组)

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

 

c++版本:

通过判断空格的个数来确定转换后的字符串长度后,我们一般会想到由前往后替换空格,但是如此之来,后面的字符需要多次移动,导致效率低下。反过来,如果由后往前进行替换,那么需要改变位置的字符只需要移动一次,时间复杂度为O(n)。

class Solution {
public:
    void replaceSpace(char *str, int length) {
        int blank = 0;
        for (int i = 0; i < length; i++) {
            if (str[i] == ' ') 
                blank++;
        }
        int newLength = length + blank * 2;
        for (int i = length - 1; i >= 0; i--) {
            if (str[i] == ' ') {
                str[--newLength] = '0';
                str[--newLength] = '2';
                str[--newLength] = '%';
            } else {
                str[--newLength] = str[i];
            }
        }
    }
};

本地IDE

#include <iostream>
using namespace std;
 
class Solution {
public:
    void replaceSpace(char *str, int length) {
        int blank = 0;
        for (int i = 0; i < length; i++) {
            if (str[i] == ' ') 
                blank++;
        }
        int newLength = length + blank * 2;
        for (int i = length - 1; i >= 0; i--) {
            if (str[i] == ' ') {
                str[--newLength] = '0';
                str[--newLength] = '2';
                str[--newLength] = '%';
            } else {
                str[--newLength] = str[i];
            }
        }
    }
};

int main() {
    // 前提是字符串的空间足够大 
    // char str[1024] = "We Are Happy";
    char *str = new char[1024];
    cout << "请输入字符串:" << endl;
    cin.getline(str, 1024);
    int length = 0, i = 0;
    while (str[length] != '\0')
        length++; 
    Solution s;
    s.replaceSpace(str, length);
    cout << "替换空格后的结果:" << endl;;
    while (str[i] != '\0') {
        cout << str[i];
        i++; 
    }
    return 0;
}

 

Python版本:

class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        return '%20'.join(s.split(' '))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值