Skip to content

Instantly share code, notes, and snippets.

@monkerek
Created June 16, 2014 13:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save monkerek/bd54cffd22ebde390a21 to your computer and use it in GitHub Desktop.
Save monkerek/bd54cffd22ebde390a21 to your computer and use it in GitHub Desktop.
1.3 Given two strings, write a method to decide if one is a permutation of the other.
# use a dict(hashmap) to count the appearance of characters of the first string, then minus the number of that in the other string.
# once the hash value is less than zero, return false
# time complexity: O(n)
# space complexity: O(1) for certain set of characters, say ascii
class Solution:
def isPermutation(self, str1, str2):
if len(str1) != len(str2):
return False
myDict = {}
for key in str1:
if myDict.has_key(key):
myDict[key] += 1
else:
myDict[key] = 1
for key in str2:
if not myDict.has_key(key):
return False
myDict[key] -= 1
if myDict[key] < 0:
return False
return True
@jackson-rz
Copy link

Line 16, myDict[key] = 1.
should be myDict[key] = 0, right?

In addition, may be you can use list instead of dict, such as:
letters = []
for i in range(256):
letters.append(0)

    for char in str1:
        letters[ord(char)] += 1

    for char2 in str2:
        letters[ord(char2)] -= 1
        if letters[ord(char2)] < 0:
            return False
    else:
        return True

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment