第六版Cracking the Coding Interview题目1.3,题目如下:
URLify: Write a method to replace all spaces in a string with '%20': You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the "true" length of the string. (Note: If implementing in Java, please use a character array so that you can perform this operation in place.)
EXAMPLE
Input: "Mr John Smith ", 13
Output: "Mr%20John%20Smith"
这道题目要求将字符串中所有空格替换为'%20',其实在Python中直接使用字符串的replace
方法即可。但题目中明确表示需要使用in place的操作,不难想到需要从字符串尾端向前进行操作。由于在Python中字符串是不可变的,先把它转换为list
之后模拟这个问题并实现如下:
def URLify(str_, trueLength):
index = trueLength + str_[:trueLength].count(' ') * 2
result = list(str_)
rear = index - 1
for head in xrange(trueLength - 1, 0, -1):
if result[head] == ' ':
result[rear - 2:rear + 1] = '%20'
rear -= 3
else:
result[rear] = result[head]
rear -= 1
return ''.join(result[:index])
在手机上阅读或分享本文请扫描以下二维码:
Comments