Checking if two strings are permutations of each other in Python

前端 未结 22 2501
旧时难觅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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 16:17

    Checking if two strings are permutations of each other in Python

    # First method
    def permutation(s1,s2):
     if len(s1) != len(s2):return False;
     return ' '.join(sorted(s1)) == ' '.join(sorted(s2))
    
    
    # second method
    def permutation1(s1,s2):
     if len(s1) != len(s2):return False;
     array = [0]*128;
     for c in s1:
     array[ord(c)] +=1
     for c in s2:
       array[ord(c)] -=1
       if (array[ord(c)]) < 0:
         return False
     return True
    

提交回复
热议问题