Checking if two strings are permutations of each other in Python

前端 未结 22 2502
旧时难觅i
旧时难觅i 2020-12-08 16:04

I\'m checking if two strings a and b are permutations of each other, and I\'m wondering what the ideal way to do this is in Python. From the Zen of

22条回答
  •  长情又很酷
    2020-12-08 16:10

    This is an O(n) solution in Python using hashing with dictionaries. Notice that I don't use default dictionaries because the code can stop this way if we determine the two strings are not permutations after checking the second letter for instance.

    def if_two_words_are_permutations(s1, s2):
        if len(s1) != len(s2):
            return False
        dic = {}
    for ch in s1:
        if ch in dic.keys():
            dic[ch] += 1
        else:
            dic[ch] = 1
    for ch in s2:
        if not ch in dic.keys():
            return False
        elif dic[ch] == 0:
            return False
        else:
            dic[ch] -= 1
    return True
    

提交回复
热议问题