剑指Offer JZ2 替换空格 C++实现

题目描述

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

解题思路


方法一:双指针

1、思路:第一反应是从头到尾遍历字符串,遇到空格则将其替换为“%20”,但是替换的字符数比空格多,这样一来就会覆盖掉后面的字符,就算提前把后续字符往后移,遇到多个空格的时候也需要多次移动,正解是先遍历一遍字符串得到空格个数,计算出新的字符串的长度,然后从后往前遍历字符串,遇到空格则反向插入“%20”,否则在对应位置插入字符串里的字符。

2、代码:

class Solution {
public:
	void replaceSpace(char *str,int length) {
        if ((str == nullptr) || (length <= 0))
            return;
        int i, cnt = 0;
        //判断空格个数
        for (i = 0; i < length; i++) {
            if (str[i] == ' ') {
                cnt++;
            }
        }
        if (cnt == 0) return;
        int new_length = length + cnt * 2 -1;
        for (i = length-1; i >= 0; i--) {
            if (str[i] == ' ') {
                str[new_length--] = '0';
                str[new_length--] = '2';
                str[new_length--] = '%';
            } else {
                str[new_length--] = str[i];
            }
        }
	}
};

3、复杂度:

时间复杂度:O(n);

空间复杂度:O(1)。


方法二:开辟辅助空间

1、思路:开辟string类型的辅助空间tmp,在string类型上进行操作,做完替换后需要将string转为char *,最后注意要将改变后的字符串赋值到原内存空间,可用char *strcpy(char *dest, const char *src)。

2、代码:

class Solution {
public:
    void replaceSpace(char *str,int length) {
        string tmp, s = str;
        for (char c : s) {
            if (c == ' ') 
                tmp += "%20";
            else 
                tmp += c;
        }
        //strcpy(str,tmp.c_str());
        strcpy(str,tmp.data());
    }
};

3、复杂度:

时间复杂度:O(n);

空间复杂度:O(n)。


方法三:调用内置函数

1、思路:直接调用string内置函数size_t find (const string& str, size_t pos = 0)和string &replace(size_t pos,size_t len,const &str)。

2、代码:

class Solution {
public:
    void replaceSpace(char *str,int length) {
        string stmp = str;
        while (stmp.find(' ') != string::npos)
            stmp.replace(stmp.find(' '), 1, "%20");
        strcpy(str,stmp.data());
    }
};

3、复杂度:

时间复杂度:O(n^2);

空间复杂度:O(n)。


方法四:正则表达式

1、思路:通过正则表达式匹配空格并替换,可用Python里的re.sub(pattern, repl, string, count=0, flags=0)。

2、代码:

# -*- coding:utf-8 -*-
import re
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        s = re.sub(r" ", "%20", s)
        return s

3、复杂度:

时间复杂度:O(n);

空间复杂度:O(1)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值