題目:請實(shí)現(xiàn)一個(gè)函數(shù)辅搬,把字符串中的每個(gè)空格替換成“%20”,例如伏尼,輸入“We are happy.”忿檩,則輸出“We%20are%20happy.”。
背景:在網(wǎng)絡(luò)編程中爆阶,如果URL參數(shù)中含有特殊字符燥透,如空格,‘#’等辨图,則可能導(dǎo)致服務(wù)器端無法獲得正確的參數(shù)值班套,需要將其轉(zhuǎn)換,規(guī)則是在‘%’后面跟上ASCII碼的兩位十六進(jìn)制表示故河,比如空格的ASCII碼為32吱韭,即十六進(jìn)制的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')
# 通過數(shù)組的查找移動(dòng)完成
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)