试图从破解python编码面试中的urlify问题编写java代码
我从urlify问题(1.3)的编码访谈中获取了Java代码: URLify:编写一个方法,用“%20”替换字符串中的所有空格。您可以假设字符串末尾有足够的空间来容纳额外的字符,并且您得到了字符串的“真实”长度。(注意:如果使用Java实现,请使用字符数组,以便可以就地执行此操作。) 范例 输入:“John Smith先生,13岁 输出:“Mr%2约翰%2史密斯” 转换后的代码有一些问题。以下是我的python代码:试图从破解python编码面试中的urlify问题编写java代码,python,arrays,algorithm,data-structures,Python,Arrays,Algorithm,Data Structures,我从urlify问题(1.3)的编码访谈中获取了Java代码: URLify:编写一个方法,用“%20”替换字符串中的所有空格。您可以假设字符串末尾有足够的空间来容纳额外的字符,并且您得到了字符串的“真实”长度。(注意:如果使用Java实现,请使用字符数组,以便可以就地执行此操作。) 范例 输入:“John Smith先生,13岁 输出:“Mr%2约翰%2史密斯” 转换后的代码有一些问题。以下是我的python代码: def urlify(str, trueLength): spaceC
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))
我不确定还有什么问题。我对这两行也有点困惑
if (trueLength < len(str)):
str[trueLength] = '\0'
缩短代码(更具python风格的方式):
说明:
string[:real_length]
# This limits strings to real length, in your case to 13. This will remove unnecessary end of the string.
.replace(' ', '%20')
# This replaces every space with '%20'.
关于您的代码:
def urlify(string, trueLength):
new_string = ''
for i in range(0, trueLength):
if string[i] == ' ':
new_string=new_string+'%20'
else:
new_string=new_string+string[i]
return new_string
我猜,贾斯汀试图理解你想要理解的代码: 请注意: 您将获得字符串的“true”长度
因此,
trueLength
可以比len(str)
短,你应该在你的代码中处理这个问题。我认为这个问题的重要部分是使用列表,因为python字符串是不可变的。你可以使用python字符串,但你应该总是创建新的,而不是更改旧的。从书中”我们使用字符数组实现了这个问题,因为Java字符串是不可变的。如果我们直接使用字符串,函数将必须返回字符串的新副本,但它将允许我们在一个过程中实现这一点。“因此,也许最好避免创建新字符串,尽管我不懂Java,但用Python创建新字符串是完全可以的。实际上,您必须创建一次新字符串—您不能更改旧字符串,但必须返回字符串,这意味着您迟早必须创建一个新字符串。最好使用我的第一个示例(Pythonic版本),但如果它对您/您的类来说太高级,那么您可以使用第二个解决方案。如果您不懂什么,请尽管问,我会解释的。另外,Python中没有字符数组。是的,您可以使用字符串创建列表,但它不限于字符,更重要的是,它不是Java或C中的内置类型。这意味着使用它代替普通字符串不会有任何好处。
def urlify(string, real_length):
return string[:real_length].replace(' ', '%20')
string[:real_length]
# This limits strings to real length, in your case to 13. This will remove unnecessary end of the string.
.replace(' ', '%20')
# This replaces every space with '%20'.
def urlify(string, trueLength):
new_string = ''
for i in range(0, trueLength):
if string[i] == ' ':
new_string=new_string+'%20'
else:
new_string=new_string+string[i]
return new_string