Valid Anagram——Hash Table

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.

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """

        #method 1
        return sorted(s) == sorted(t)

        #method 2
        dic = {}
        for item in s:
        	dic[item] = dic.get(item,0) + 1
        for item in t:
        	dic[item] = dic.get(item,0) - 1
        return True if dic.values().count(0) == len(dic) else False

猜你喜欢

转载自qu66q.iteye.com/blog/2317220