首页 > 解决方案 > 尝试从破解python中的编码面试中的urlify问题编写java代码

问题描述

我从破解 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

标签: pythonarraysalgorithmdata-structures

解决方案


缩短代码(更多 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

推荐阅读