'''
先遍历整个字符串,计算字符串中空格的总数,从而可以计算出替换后的字符串长度
(根据替换规则,每次替换空格时,都会使字符串的长度增加2)。然后,使用两个指针或索引,从后往前遍历,
即初始化指针或索引分别指向替换前和替换后字符串的末尾,循环递减,如遇到空格,则替换为 "%20",
从而减少字符串移动的次数,降低时间复杂度。
'''
def replace_blanks(string):
if string == None :
return
# Count the number of blanks
blanks_count = string.count(' ')
string_length = len(string)
# Compute the replaced string length
replaced_length = string_length + 2 * blanks_count
# Extend the char list length 'string_length' with '' characters
string += ["" for i in range(replaced_length - string_length)]
print(string)
# Replace each blank with "%20"
original_index = string_length - 1
new_index = replaced_length - 1
while new_index != original_index:
if string[original_index] == ' ':
new_index -= 2
string[new_index:new_index+3] = '%20'
else:
string[new_index] = string[original_index]
# Update indexes
new_index -= 1
original_index -= 1
def unitest():
test_string = "We are happy."
string_lst = list(test_string) # 易错点,不能用'str'对象替代,因为 'str' object does not support item assignment 。
# print "Before replacing blanks, the string is %s" % ''.join(string_lst)
print("Before the string is % s"% ''.join(string_lst))
replace_blanks(string_lst, 100)
# print "After replacing blanks, the string is %s" % ''.join(string_lst)
print("After the string is % s"% ''.join(string_lst))
if __name__ == '__main__':
unitest()