【发布时间】:2019-01-09 03:43:09
【问题描述】:
我从破解urlify问题(1.3)的编码面试中获取的Java代码:
URLify:编写一个方法,用 '%20' 替换字符串中的所有空格。您可以假设字符串末尾有足够的空间来容纳其他字符,并且您得到了字符串的“真实”长度。 (注意:如果用Java实现,请使用字符数组,以便您可以就地执行此操作。)
示例
输入:“约翰·史密斯先生,13 岁
输出:“%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))
我认为问题之一是
str[trueLength] = '\0'
我不确定还有什么问题。我对这两行也有点困惑
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 arrays algorithm data-structures