Checking if two strings are permutations of each other in Python

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

    Here's martinus code in python. It only works for ascii strings:

    def is_permutation(a, b):
        if len(a) != len(b):
            return False
    
        char_count = [0] * 256
        for c in a:
            char_count[ord(c)] += 1
    
        for c in b:
            char_count[ord(c)] -= 1
            if char_count[ord(c)] < 0:
                return False
    
        return True
    

提交回复
热议问题