[编程题]替换空格

//思路
//1：从前往后插入，这样移动·的次数多不建议
//2：从后往前插入

class Solution {
public:
void replaceSpace(char *str,int length) {
//遍历一边字符串找出空格的数量
if(str==NULL||length<0)
return ;
int i=0;
int oldnumber=0;//记录以前的长度
int replacenumber=0;//记录空格的数量
while(str[i]!='\0')
{
oldnumber++;
if(str[i]==' ')
{
replacenumber++;
}
i++;
}
int newlength=oldnumber+replacenumber*2;//插入后的长度
if(newlength>length)//如果计算后的长度大于总长度就无法插入
return ;
int pOldlength=oldnumber; //注意不要减一因为隐藏个‘\0’也要算里
int pNewlength=newlength;
while(pOldlength>=0&&pNewlength>pOldlength)//放字符
{
if(str[pOldlength]==' ') //碰到空格就替换
{
str[pNewlength--]='0';
str[pNewlength--]='2';
str[pNewlength--]='%';

}
else //不是空格就把pOldlength指向的字符装入pNewlength指向的位置
{
str[pNewlength--]=str[pOldlength];

}
pOldlength--; //不管是if还是elsr都要把pOldlength前移

}

}
};

import re
class Solution:
# s 源字符串
def replaceSpace(self, s):
r = re.sub(' ','%20',s)
return r

# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
s = list(s)
spacenum = 0
for c in s:
if c==' ':
spacenum += 1
extraspace = spacenum*2
s = s + [' ']*extraspace
slen = len(s)
search_p = slen-extraspace-1
store_p = slen-1
while(search_p>=0):
if s[search_p] == ' ':
s[store_p-2:store_p+1] = '%20'
store_p  = store_p-3
else:
s[store_p] = s[search_p]
store_p = store_p - 1
search_p = search_p-1
return ''.join(s)

# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
count = 0
for si in s:
if si == ' ':
count += 1
new_len = len(s) + count*2
new_s = [0] * new_len
p1 = len(s)-1
p2 = new_len - 1
while p1 >= 0 and p2 >=0:
if s[p1] == ' ':
new_s[p2]= '0'
new_s[p2-1]= '2'
new_s[p2-2]= '%'
p2 -= 3
else:
new_s[p2]= s[p1]
p2 -= 1
p1 -= 1
return ''.join(new_s)
'''
if ' ' in s:
s = s.replace(' ', '%20')
return s
'''

"""

""" class Solution: def replaceSpace(self, s): # 原地修改 s = s.replace(' ', '%20') return s """ 方案二  """ class Solution: def replaceSpace(self, s): tr = ' '  # 创建一个空串 for item in range(len(s)): # 遍历s if s[item] == ' ':  # 判断是否为空 tr += '%20'  # 在新串中累加 else: tr += s[item]  # 在新串中累加不为空的 return str

# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
s = str(s)
s = s.replace(' ', '%20')
return s

def info2():      str_info="We Are Happy"  str_replace=str_info.replace(" ","%20")
return str_replace

class Solution:
def replaceSpace(self, s):
# write code here
if not isinstance(s,str)or len(s) <= 0 or s == None:
return ''
space_num = 0
for i in s:
if i == ' ':
space_num += 1
new_len = len(s) + space_num*2
new_str = [None]*new_len
i = 0
for j in range(len(s)):
if s[j] == ' ':
new_str[i:i+3] = ['%','2','0']
i += 3
else:
new_str[i] = s[j]
i += 1
return ''.join(new_str)

python 思路：

# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
return '%20'.join(s.split(' '))

class Solution:
# s 源字符串
def replaceSpace(self, s):
i=0
while(i!=len(s)):
if s[i] == ' ':
s=s[0:i]+'%20'+s[i+1:]
i+=2
i+=1
return s

py大法好...
return(char.replace(' ','%20'))

# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
s2 = []
for i in range(len(s)):
if s[i] == ' ':
s2.append("%20")
else:
s2.append(s[i])
return "".join(s2)

class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
list = []
list = s.split(' ')
n = len(list)
new_s = list[0]
for v in range(1, n):
new_s += '%20'
new_s += list[v]
return new_s

S = Solution()
while True:
try:
my_str = raw_input()
print(S.replaceSpace(my_str))
except:
break

# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
rep_str = '%20' # 替换的字符
space_nums = 0 # 空格个数
for i in s:
if i == ' ':
space_nums += 1
lens = len(s) # 原始字符串长度
rep_lens = lens+(len(rep_str)-1)*space_nums # 替换后的长度
s = list(s)+['0']*(rep_lens-lens)
p1 = lens-1 # p1指向原始字符串最后一位
p2 = rep_lens-1 # p2指向替换后字符串的最后一位
while p1 != p2:
if s[p1] != ' ':
s[p2] = s[p1]
p1 -= 1
p2 -= 1
else:
s[(p2-len(rep_str)+1):(p2+1)] = rep_str
p2 = p2-len(rep_str)
p1 -= 1
return ''.join(s)

python3种方法：

1：
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
s=list(s)
for i,item in enumerate(s):
if item == " ":
s[i]='%20'
return "".join(s)
2：
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
return s.replace(" ","%20")

3：
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
originalLength=len(s)
blankNum=0
for item in s:
if item==" ":
blankNum+=1
newLength=originalLength+blankNum*2
s=list(s)
s+=['#']*2*(blankNum+1)
while originalLength>=0 and newLength>=originalLength:
if s[originalLength]==" ":
s[newLength]="0"
newLength-=1
s[newLength]='2'
newLength-=1
s[newLength]="%"
newLength-=1
else:
s[newLength]=s[originalLength]
newLength-=1
originalLength-=1
return "".join(s).rstrip('#')

Python，一行搞定：
# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
return s.replace(' ', "%20")

class Solution:
def replaceSpace(self, s):
string =''
for i in s:
if i == ' ':
i= '%20'
string +=i
else:
string +=i
return string

# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
temp = s.split(" ")
results = ""
length = len(temp)
for i in range(length):
results += temp[i]
if i < (length -1):
results += "%20"
return results

# -*- coding:utf-8 -*- class Solution:  # s 源字符串  def replaceSpace(self, s):  # write code here  res= ''  for charin s:  if char== ' ':  res+= '%20'  else:  res +=char returnres

python

def replaceSpace(self, s):
# write code here
if not s:
return s
if not isinstance(s,str):
return
s1 = ''
for item in s:
if item == ' ':
s1 += '%20'
else:
s1 += item
return s1

# -*- coding:utf-8 -*-
class Solution:
# s 源字符串
def replaceSpace(self, s):
return s.replace(' ',"%20")

135条回答 506074浏览

# 通过挑战的用户

• 2019-07-23 11:31:08
• 2019-07-23 11:30:33
• 2019-07-23 11:28:47
• 2019-07-23 11:25:04
• 2019-07-23 11:23:35

# 相关试题

• 扫描二维码，关注牛客网

• 下载牛客APP，随时随地刷题