Skip to content

Commit

Permalink
Create valid-anagram.py
Browse files Browse the repository at this point in the history
  • Loading branch information
kamyu104 committed Aug 1, 2015
1 parent bb1b92a commit 5361740
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions Python/valid-anagram.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Time: O(n)
# Space: O(1)
#
# Given two strings s and t, write a function to
# determine if t is an anagram of s.
#
# For example,
# s = "anagram", t = "nagaram", return true.
# s = "rat", t = "car", return false.
#
# Note:
# You may assume the string contains only lowercase alphabets.
#

class Solution:
# @param {string} s
# @param {string} t
# @return {boolean}
def isAnagram(self, s, t):
if len(s) != len(t):
return False

count = {}

for c in s:
if c.lower() in count:
count[c.lower()] += 1
else:
count[c.lower()] = 1

for c in t:
if c.lower() in count:
count[c.lower()] -= 1
else:
count[c.lower()] = -1
if count[c.lower()] < 0:
return False

return True

# Time: O(nlogn)
# Space: O(n)
class Solution2:
# @param {string} s
# @param {string} t
# @return {boolean}
def isAnagram(self, s, t):
return sorted(s) == sorted(t)

0 comments on commit 5361740

Please sign in to comment.