python - 破解python编码面试中urlify问题尝试写java代码

标签 python arrays algorithm data-structures

我从破解 urlify 问题(1.3)的编码面试中获取了 Java 代码:

URLify:编写一个方法将字符串中的所有空格替换为“%20”。您可能会假设字符串末尾有足够的空间来容纳额外的字符,并且给定了字符串的“真实”长度。 (注意:如果用Java实现,请使用字符数组,以便您可以原地执行此操作。)

例子

输入:“John Smith 先生,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))

我认为其中一个问题是

str[trueLength] = '\0'

我不确定还有什么问题。我也对这两条线有点困惑

if (trueLength < len(str)):
        str[trueLength] = '\0'

所以如果有人能解释这些台词,那就太棒了。我只是想完全理解 Gayle 的解决方案。


我找到的代码:

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

最佳答案

缩短代码(更 Pythonic 的方式):

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'.

关于您的代码:

  1. 在 Python 中,'str' 是保留字。不要使用它。

  2. 在 Python 中,您不能更改字符串。您必须创建一个新的。不支持字符串项分配。您的代码完全基于项目分配。您应该改为创建新字符串并向其添加字符。

  3. 这段代码真的很乱。很难理解,你应该找到更简单的解决方案。

您的代码和逻辑已优化:

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

关于python - 破解python编码面试中urlify问题尝试写java代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54102942/

相关文章:

c++ - 数组内的自增运算符

python - 如何自定义 Flask admin QuerySelectMultipleField 选择?

python - 在 Pandas 中使用多索引标题读取 excel 时选择列

c - 如何将 char 数组转换为 C 中的字符串?

c++ - 为什么函数返回空对象?

c++ - 优化找到特定斐波那契数的算法

c++ - 从数组中抽取非重复随机元素的有效算法

Python - 实现 __iter__ 或返回列表的 __iter__

python - Ubuntu 中的 PDF 到 PPT 转换器

c# - 如何动态生成和填充多维数组