Check Two Strings are Anagrams?

class Solution(object):
    def isAnagram(self, s, t):
        :type s: str
        :type t: str
        :rtype: bool
        # Keep a frequency array
        frequency = {}
        for c in s:
            if c not in frequency:
                frequency[c] = 1
                frequency[c] += 1
        # Go over the other string 
        for d in t:
            if d in frequency:
                frequency[d] -= 1
                if frequency[d] == 0:
                    # Just keep deleting what is not required
                    del frequency[d]
                # Anything not in dict, just say Not an Anagram.
                return False

        if len(frequency) == 0:
            return True
        return False

Written with StackEdit.

Leave a Reply

Please log in using one of these methods to post your comment: Logo

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

Google photo

You are commenting using your Google 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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: