[剑指Offer]替换空格

本文首发于我的个人博客Suixin’s Blog
原文: https://suixinblog.cn/2019/02/target-offer-replace-space.html  作者: Suixin

题目描述

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

解题思路

略。

代码

Python(2.7.3)

# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        if not isinstance(s, str):
            return s
        s_new = ''
        for i in s:
            if i == ' ':
                s_new += '%20'
            else:
                s_new += i
        return s_new

运行时间:25ms
占用内存:5736k

猜你喜欢

转载自blog.csdn.net/weixin_43269020/article/details/88045282