Created
June 16, 2014 13:10
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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)