第2章 面试需要的基础知识
面试题4:二维数组中的查找
面试题5:替换空格
第3章 高质量的代码
第4章 解决面试题的思路
第5章 优化时间和空间效率
第6章 面试中的各项能力
第7章 两个面试案例
题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
解题思路
由于Python不能对字符串赋值,所以常规解法必须使用O(n)辅助空间,可以新建一个字符串,对原字符串遍历时遇到空格便加上‘20%’,否则直接赋值原字符。
Python中有很多对字符串的操作,比如replace(),sub()等,还可以对空格split得到list,用‘%20’连接(join)这个list。
实战
牛客网 替换空格
常规解法:
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
new_s = ''
for st in s:
if st == ' ':
new_s += '%20'
else:
new_s += st
return new_s
replace()解法:
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
return s.replace(' ', '%20')
sub()解法:
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
import re
return re.sub(' ', '%20', s)
数组解法:
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
lst = s.split(' ')
return '%20'.join(lst)