我从破解urlify问题(1.3)的编码面试中获取了Java代码:
URLify:编写一个方法,将字符串中的所有空格替换为“%20”。您可以假设字符串的末尾有足够的空间来容纳额外的字符,并且为您提供了字符串的“真”长度。(注意:如果用Java实现,请使用字符数组以便您可以就地执行此操作。)
示例
输入:“约翰·史密斯先生,13岁
输出:“Mr%2eJohn%2eSmith”
我对转换后的代码有一些问题。下面是我的python代码:
def urlify(str, trueLength):
spaceCount = 0
index = 0
i = 0
for i in range(0, trueLength):
if str[i] == ' ':
spaceCount += 1
print(spaceCount, "spaceCount")
index = trueLength + spaceCount * 2
if (trueLength < len(str)):
str[trueLength] = '\0'
for i in range(trueLength, 0):
if str[i] == ' ':
str[index - 1] = '0'
str[index - 2] = '2'
str[index - 3] = '%'
index = index - 3
else:
str[index - 1] = str[i]
index = index - 1
print(urlify("Mr John Smith ", 13))
我认为问题之一是
^{pr2}$我不知道还有什么问题。我对这两条线也有点困惑
if (trueLength < len(str)):
str[trueLength] = '\0'
所以如果有人能解释这些台词,那就太棒了。我只是想完全理解盖尔的解决方案。在
我发现的代码:
def urlify(string, length):
'''function replaces single spaces with %20 and removes trailing spaces'''
new_index = len(string)
for i in reversed(range(length)):
if string[i] == ' ':
# Replace spaces
string[new_index - 3:new_index] = '%20'
new_index -= 3
else:
# Move characters
string[new_index - 1] = string[i]
new_index -= 1
return string
缩短代码(更多python方式):
说明:
^{pr2}$关于您的代码:
在Python中,“str”是保留字。不要用它。
在Python中,不能更改字符串。你必须创建一个新的。不支持字符串项分配。您的代码完全基于项分配。您应该创建新的字符串并向其添加字符。
这个代码真是一团糟。这很难理解,你应该找到更简单的解决办法。
您的代码和逻辑已优化:
我猜,贾斯汀试图理解你想理解的代码:
请注意:
因此
trueLength
可以比len(str)
短,您应该在代码中处理这种情况。在相关问题 更多 >
编程相关推荐