1.问题描述:
设计一种方法,将一个字符串中的所有空格替换成 %20
。你可以假设该字符串有足够的空间来加入新的字符,且你得到的是“真实的”字符长度。你的程序还需要返回被替换后的字符串的长度。
2.样例:
样例 1:
输入:string[] = "Mr John Smith" and length = 13
输出:string[] = "Mr%20John%20Smith" and return 17
解释:
对于字符串 "Mr John Smith",长度为 13。替换空格之后,参数中的字符串需要变为 "Mr%20John%20Smith",并且把新长度 17 作为结果返回。
样例 2:输入:string[] = "LintCode and Jiuzhang" and length = 21
输出:string[] = "LintCode%20and%20Jiuzhang" and return 25
解释:
对于字符串 "LintCode and Jiuzhang",长度为 21。替换空格之后,参数中的字符串需要变为 "LintCode%20and%20Jiuzhang",并且把新长度 25 作为结果返回。
3.代码:
class Solution:
"""
@param: string: An array of Char
@param: length: The true length of the string
@return: The true length of new string
"""
def replaceBlank(self, string, length):
# write your code here
if string is None: return None
for char in string:
if char == '':
break
if char != ' ':
string += char
else:
string.append('%')
string.append('2')
string.append('0')
for i in range(length):
string.pop(0)
return len(string)
本题解题思路中使用循环去判断空格位置,如果遇到空格就append(%20)。在原始的string的上进行操作的话,可以先把循环的结构都append到string后面,在循环结束后,再使用pop将不需要的char弹出数组。这里使用pop(0),代表从队列首部开始弹出,默认是‘-1’表示从队尾弹出。
本题需要注意的点比较多,如下所示:
1.答案只返回新字符串的长度,并检查原字符串。
2.字符串以列表的形式给出,并不能使用split。
3.不清楚检查机制,但经过多次试错发现应该是以id(string)来检查原来的字符串string的,所以不能生成新的字符串再赋值。
4.pop() 默认参数为 -1 即从队尾出列,可使用 pop(0) 从队头出列。
5.为保证长度正确以及避免编译器不认,分三次append。
参考链接:
1. https://www.jianshu.com/p/759796a32904