题目:请实现一个函数,把字符串中的每个空格替换成“%20”,例如,输入“We are happy.”,则输出“We%20are%20happy.”。
背景:在网络编程中,如果URL参数中含有特殊字符,如空格,‘#’等,则可能导致服务器端无法获得正确的参数值,需要将其转换,规则是在‘%’后面跟上ASCII码的两位十六进制表示,比如空格的ASCII码为32,即十六进制的0x20,因此空格被替换为‘%20’。
# pythonic的方法
class Solution:
def change_blank_a(self, s):
if s is not None:
return '%20'.join(s.split(' '))
def change_blank_b(self, s):
if s is not None:
return s.replace(' ', '%20')
# 通过数组的查找移动完成
class Solution:
def change_blank(self, s):
if s is None:
raise Exception("wrong")
s = list(s)
count = 0
length = 0
for i in s:
length += 1
if i is ' ':
count += 1
new_length = length + 2 * count
s = s + [None] * 2 * count
p = length - 1
q = new_length - 1
while p >= 0 and q >= 0:
if s[p] is not ' ':
s[q] = s[p]
p -= 1
q -= 1
else:
s[q-2:q+1] = '%20'
p -= 1
q -= 3
return ''.join(s)
网友评论