Valid Anagram - (变位词)

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.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

class Solution:
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if len(s) != len(t):
            return False
        d = {}
        for i in range(len(s)):
            if s[i] not in d:
                d[s[i]] = 1
            else:
                d[s[i]] += 1
        for i in range(len(t)):
            if t[i] not in d:
                return False
            else:
                d[t[i]] -= 1
        for k, v in d.items():
            if v < 0:
                return False
        return True
class Solution:
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if len(s) != len(t):
            return False
        
        if set(s) != set(t):
            return False
        
        for ch in set(s):
            if s.count(ch) != t.count(ch):
                return False
        return True  

你可能感兴趣的:(Valid Anagram - (变位词))