Checking if two strings are permutations of each other in Python

前端 未结 22 2500
旧时难觅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:25

    Here is a way which is O(n), asymptotically better than the two ways you suggest.

    import collections
    
    def same_permutation(a, b):
        d = collections.defaultdict(int)
        for x in a:
            d[x] += 1
        for x in b:
            d[x] -= 1
        return not any(d.itervalues())
    
    ## same_permutation([1,2,3],[2,3,1])
    #. True
    
    ## same_permutation([1,2,3],[2,3,1,1])
    #. False
    

提交回复
热议问题