牛客网-剑指offer(二 )替换空格

牛客网剑指offer第二题,替换空格,原地址在这https://www.nowcoder.com/ta/coding-interviews

想要练习的小伙伴可以去练习,期待大家都能拿到好的offer。

题目:请实现一个函数,将一个字符串中的空格替换成“%20”。

例如,当字符串为We Are Happy.

则经过替换之后的字符串为We%20Are%20Happy。

对python来说,只需要将字符串转成list,然后将空格处变成%20就可以了,但这样也失去了算法的意义。

下面记录一下思路,截图取自剑指offer这本书,推荐购买正版。

当然还得问一下,需不要不新建立一个字符串,还是直接在原来的字符串上修改。在原来字符串上修改呢,

一般刚开始想到的就是从头到尾遍历,遇到空格就添加‘%20’,但是这样后面的字符需要集体往后面移,这样时间复杂度是O(n2),如果从后面忘前面遍历,时间复杂度只有O(n)。如下图所示:

牛客网-剑指offer(二 )替换空格_第1张图片

c++代码如下所示:

#include
using namespace std;
class Solution {
public:
	void replaceSpace(char *str,int length) {
        if(str==NULL||length<0)
            return ;
        int i = 0;
        int ori_length = 0;
        int space_length = 0;
        while(str[i] != '\0'){
            ++ori_length;
            if (str[i]== ' ')
                space_length++;
            ++i;
        }
//	cout << space_length <= 0 && new_index > ori_index){
            if (str[ori_index] == ' '){
                str[new_index--] = '0';
                str[new_index--] = '2';
                str[new_index--] = '%';
                }
            else{
               str[new_index--] = str[ori_index];
            }
            ori_index--;
//	cout << ori_index <

而对python来说,就没有那么复杂

# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        s = list(s)
        count=len(s)
        for i in range(0,count):
            if s[i]==' ':
                s[i]='%20'
        return ''.join(s)

你可能感兴趣的:(笔试面试相关)