1. 程式人生 > >LeetCode242:Valid Anagram

LeetCode242:Valid Anagram

Given two strings s and , write a function to determine if t is an anagram of s.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: 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?


LeetCode:連結

直觀的思路是,統計兩個字串中不同字元出現的次數,只有當兩者出現的字元相同且出現的次數相同,那麼它們是“anagram”。另外,兩個長度不同的字串一定不滿足要求,可以輔助判斷。 

通用的方法應該用字典處理,對於unicode也可以處理。分別對s和t生成兩個字典,判斷字典是否相同即可。

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if len(s) != len(t):
            return False

        def count(s):
            dict = {}
            for i in range(len(s)):
                if s[i] not in dict:
                    dict[s[i]] = 1
                else:
                    dict[s[i]] += 1
            return dict

        dict_s = count(s)
        dict_t = count(t)
        return dict_s == dict_t

更簡單的寫法,Python 字典(Dictionary) get() 函式返回指定鍵的值,如果值不在字典中返回預設值

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if len(s) != len(t):
            return False

        alpha = {}
        beta = {}
        for c in s:
            alpha[c] = alpha.get(c, 0) + 1
        for c in t:
            beta[c] = beta.get(c, 0) + 1
        return alpha == beta