同构字符串(简单的方法?)

2024-06-16 12:35:36 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我一直在努力解决Leetcode上的简单问题,到目前为止,我在互联网上找到的大多数答案我都不明白。我试图解决同构字符串问题(这里:https://leetcode.com/problems/isomorphic-strings/description/) 我想出了下面的代码

def isIso(a,b):
        if(len(a) != len(b)):
                return false
        x=[a.count(char1) for char1 in a]
        y=[b.count(char1) for char1 in b]
        return x==y                   
string1 = input("Input string1..")
string2 = input("Input string2..")
print(isIso(string1,string2))

现在我明白这可能是你一整天看到的最愚蠢的代码,但这有点像我的意思。我想知道为什么这是错误的(在哪里),以及我应该如何进一步发展。在


Tags: 答案代码inforinputlenreturncount
2条回答

您可以使用两个dict来跟踪a中每个字符到{}的映射,以及{}中每个字符到{}的映射,如果对应字符中有任何冲突,则返回False;否则最后返回{}。在

def isIso(a, b):
    m = {} # mapping of each character in a to b
    r = {} # mapping of each character in b to a
    for i, c in enumerate(a):
        if c in m:
            if b[i] != m[c]:
                return False
        else:
            m[c] = b[i]
        if b[i] in r:
            if c != r[b[i]]:
                return False
        else:
            r[b[i]] = c
    return True

因此:

^{pr2}$

输出将:

True
False
True
False

如果我正确地理解了这个问题,因为一个字符可以映射到它自己,这只是一个例子,看看这两个单词的字符计数是否相同。在

所以egg和add是同构的,因为它们的字符数是(1,2)。类似地,论文和标题的计数为(1,1,1,2)。在

1,2是同构的。在

为了查看字符数是否相同,我们需要对它们进行排序。在

所以:

from collections import Counter
def is_isomorphic(a,b):
    a_counts = list(Counter(a).values())
    a_counts.sort()
    b_counts = list(Counter(b).values())
    b_counts.sort()
    if a_counts == b_counts:
        return True
    return False

您的代码失败是因为:

^{pr2}$

计算字符串中每个字符的出现次数。所以像‘奇数’这样的单词不会有(1,2)的计数,而当你数到d两次时,它会有(1,2,2)!在

相关问题 更多 >