One is permutation of the other

Problem: Given two strings, write a method to decide if one is a permutation of the other

def isPermutation(str1,str2):
    if len(str1) != len(str2):
        return False
    else:
        str1Sorted = "".join(sorted(str1))
        str2Sorted = "".join(sorted(str2))
        if str1Sorted == str2Sorted:
            return True
        else:
            return False

print isPermutation("god","dog")
print isPermutation("god","logged")

def isPermutation2(str1,str2):
    if len(str1) != len(str2):
        return False
    else:
        isPerm = True
        arr = [0]*256
        for entries in str1:
            arr[ord(entries)] += 1

        for entries in str2:
            arr[ord(entries)] -= 1

        for entries in arr:
            if entries != 0:
                isPerm = False
   return isPerm

print isPermutation("god","dog")
print isPermutation("god","logged")

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s