剑指offer——面试题5:替换空格

面试题5:替换空格

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

解法1(python)

  • 直接使用replace函数
# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        return s.replace(' ', '%20')

解法2(python)

  • 使用一个列表来转换, 遍历一遍字符串,这个将字符添加至列表中,若遇到‘ ’,则添加%20
# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        # return s.replace(' ', '%20')
        strLen = len(s)
        strList = []
        for i in range(strLen):
            if s[i] == ' ':
                strList.append('%20')
            else:
                strList.append(s[i])
        return ''.join(strList)

解法3(C++)

  • 思路: 若是在原字符串上进行的情况,需要从后往前替换, 这样的时间复杂度为O(n); 而从前往后的复杂度为 O ( n 2 ) O(n^2) O(n2),不建议使用。
    (1)遍历一遍字符串,统计空格数,即可计算出替换后的字符串长度
    (2)准备两个指针p1和p2,p1指向原字符串末尾,p2指向替换后的字符串末尾
    (3)p1逐渐往前移动,同时将指向的字符复制到p2处,p2也对应的向前移动, 若p1遇到了空格,则p1向前移动一格, p2处插入"%20",同时p2往前移动3格。
    (4)若p1和p2指向同一位置, 则完成
class Solution {
public:
	void replaceSpace(char *str,int length) {
        if (str == nullptr || length <= 0)
            return;
        int oldLen = 0; // 统计原字符串长度
        int blankLen = 0;  // 统计空格数
        int i = 0;
        while(str[i] != '\0')
        {
            ++oldLen;
            if(str[i] == ' ')
                ++blankLen;
            ++i;
        }
        
        int newLen = oldLen + 2*blankLen;  // 计算替换后的字符串长度
        int indexOld = oldLen;
        int indexNew = newLen;
        while(indexOld != indexNew)
        {
            if(str[indexOld] != ' ')
            {
                str[indexNew] = str[indexOld];
                indexNew--;
                indexOld--;
            }
            else
            {
                str[indexNew--] = '0';
                str[indexNew--] = '2';
                str[indexNew--] = '%';
                indexOld--;
            }
        }
	}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值