2 字符串替换空格
牛客网
python
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy. 则经过替换之后的字符串为We%20Are%20Happy。(直接在字符串上修改)
# -*- coding:utf-8 -*-
import numpy as np
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
len_s=len(s)-1
s1=list(s)
t=[] # 保存空格索引
for i in range(len_s,-1,-1):
if s1[i]==' ':
t.append(i)
len_t=len(t)
q=len_s+1
for j in range(len_t): # 先把内存分配好
s1.append(' ')
s1.append(' ')
for j in range(len_t):
p=t[j]
for i in range(q-1,p,-1):# 从后往前 移动
index=i+2*(len_t-j)
print(i,index,s1[i])
s1[index]=s1[i]
index=p+1+2*(len_t-j)
s1[index-3]='%'
s1[index-2]='2'
s1[index-1]='0'
q=p
s=''.join(s1)
return s
s=' hello world '
print(s)
task1=Solution()
t=task1.replaceSpace(s)
print(t)