从字符串中的每个单词中删除重复的字母



我正在准备面试。假设我想从字符串中删除重复的字母,我想出了两个函数来实现这一点:

# option 1:
def checkDuplicates(string):
    postCheck = ""
    previousChar = None
    for currentChar in string:
        if currentChar != previousChar:
            postCheck += currentChar
            previousChar = currentChar
    return postCheck.title()
# option 2:
def checkDuplicates2(string):
    scanned = set()
    postCheck = ""
    for currentChar in string:
        if currentChar not in scanned:
            scanned.add(currentChar)
            postCheck += currentChar
    return postCheck.title()

测试:

>>> print(checkDuplicates("llaatteerr")
Later
>>> print(checkDuplicates2("llaatteerr")
Later

现在让我们假设我想做同样的事情,但在一个字符串上,我必须循环遍历字符串中的每个单词。如果一个单词中有重复的字符,请删除重复的字符。如果第二个单词包含第一个单词中的字符,那也没关系——每个单词都有自己的大小写。例如:

>>> checkDup("llaatteerr tthhoouugghhtt")
Later Thought

因此,为了做到这一点,我创建了第二个函数:

def checkDupInWords(words):
    postCheck = ""
    for word in words.split():
        postCheck += f"{checkDuplicates(word)} "
    return postCheck

测试:

>>>print(checkDupInWords("llaatteerr llaatteerr llaatteerr"))
Later Later Later

现在我的问题是,如果一个单词包含重复的字母,并且它们是有意义的重复(即"莱昂纳多"(,这是一项短期内可完成且值得追求的任务吗?还是需要语言学知识和使用外部图书馆?

额外的问题:有人会说在面试中或在一份普通的软件开发工作中有可能遇到这样的任务吗!

现在我的问题是,如果一个单词包含重复的字母它们是有意义的复制品(即"莱昂纳多"(

我对重复字母的解释是一个单词中出现两次或两次以上的字母,而不一定是相邻的。

这是一项短期内可完成且值得追求的任务吗?

任务本身肯定是可行的,值得追求。

如果你遇到这样的问题,你也应该在制定解决方案之前先澄清一下,以防你对任务的理解与面试官的意思不一致。ps。我也不知道这个问题是否真的属于这里,这是一个奇怪的问题。

最新更新