Checking if two strings are permutations of each other in Python

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

    from collections import defaultdict
    def permutation(s1,s2):
        h = defaultdict(int)
        for ch in s1:
            h[ch]+=1
        for ch in s2:
            h[ch]-=1
        for key in h.keys():
            if h[key]!=0 or len(s1)!= len(s2):
                return False
            return True
    print(permutation("tictac","tactic"))
    

提交回复
热议问题