替换空格
来源:互联网 发布:网络信息有限公司 编辑:程序博客网 时间:2024/06/09 17:44
牛客网 《剑指offer》
时间限制:
1秒
空间限制:32768K
热度指数:378402
本题知识点: 字符串
题目描述
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
解题思路
参考别人的Python实现
https://github.com/Jack-Lee-Hiter/AlgorithmsByPython/blob/master/Target%20Offer/%E6%9B%BF%E6%8D%A2%E7%A9%BA%E6%A0%BC.py
'''请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。'''# -*- coding:utf-8 -*-class Solution: # s 源字符串 # 创建新的字符串进行替换 def replaceSpace1(self, s): tempstr = '' if type(s) != str: return for c in s: if c == ' ': tempstr += '%20' else: tempstr += c return tempstr # 简单代码替换 # 在Python中str类型是不可变的类型, 使用replace语句会生成一个新的str, 原始的s还是带空格的str变量 def replaceSpace2(self, s): if type(s) != str: return return s.replace(' ', '%20') # 书中给的思路 # 判断输入类型的时候,isinstance必须首先判断,因为如果输入为integer的话,没有len,就会直接报错 def replaceSpace3(self, s): if not isinstance(s,str) or len(s) <= 0 or s == None: return "" spaceNum = 0 for i in s: if i == " ": spaceNum += 1 newStrLen = len(s) + spaceNum * 2 newStr = newStrLen * [None] indexOfOriginal, indexOfNew = len(s) - 1, newStrLen - 1 while indexOfNew >= 0 and indexOfNew >= indexOfOriginal: if s[indexOfOriginal] == ' ': newStr[indexOfNew-2:indexOfNew+1] = ['%', '2', '0'] indexOfNew -= 3 indexOfOriginal -= 1 else: newStr[indexOfNew] = s[indexOfOriginal] indexOfNew -= 1 indexOfOriginal -= 1 return "".join(newStr)s = 'we are happy'test = Solution()print(test.replaceSpace1(s))print(test.replaceSpace2(s))print(test.replaceSpace3(s))
阅读全文
0 0
- 空格替换
- 替换空格
- 空格替换
- 替换空格
- 替换空格
- 替换空格
- 替换空格
- 替换空格
- 替换空格
- 替换空格
- 替换空格
- 空格替换
- 替换空格
- 替换空格
- 替换空格
- 替换空格
- 替换空格
- 替换空格
- 我的第一个web小程序
- bzoj 2186(欧拉函数)
- 百度 核心系统工程师 2017校招笔试
- 浅谈虚拟机与物理机
- poj-Wireless Network
- 替换空格
- hdu 4856 Tunnels(bfs+状态压缩)
- Spring的BeanFactoryPostProcessor和BeanPostProcessor
- 缓存系统之Redis
- 设计模式之享元模式
- 面试题02:Delete occurrences of an element if it occurs more than n times
- NoSQL基础理论
- OpenSSL及CA加密
- Java SE 、Java EE和 Java ME的区别