请实现一个函数,将一个字符串中的空格替换成“%20”。
例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy
class Solution():
def replaceblank(array):
count = 0
for i in range(array):
if i == " ":
count += 1
newlength = len(array) + count * 2
i = j = 0
while i < len(array) and j < len(newlength):
if array[i] == " ":
newlength[j] = "2"
j += 1
newlength[j] = "0"
j += 1
newlength[j] = "%"
j += 1
i += 1
else:
newlength[j] = array[i]
return newlength
package problem004
func replaceSpace(str []byte, length int) {
count := 0
// 遍历一遍字符串, 统计字符出现的数目, 计算替换后的字符串长度
for i:=0; i<length; i++ {
if str[i] == ' '{
count++
}
}
newlength := length + count*2
// 两个index,一个指向length-1, 另一个指向newlength-1,遍历一遍字符串,完成替换
for l,nl := length-1,newlength-1; l>=0 && nl>=0; {
if str[l]==' '{
str[nl] = '0'
nl--
str[nl] = '2'
nl--
str[nl] = '%'
nl--
l--
} else {
str[nl] = str[l]
nl--
l--
}
}
}









网友评论