[LeetCode][Python]242. 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?

思路分析:

anagram的翻译就是 变位词;(变换或颠倒字母顺序而成另一词的)回文构词法

所以s和t的字母应该是一致的,只是字母顺序不一样。直觉上可以判断t中的每个元素是不是都在t里面,如果是,就返回true,否则就返回false。

考虑到元素一样,顺序不一致。还可以对s,t进行排序,以及使用系统自带的collections.Counter()

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        import collections
        return collections.Counter(s) == collections.Counter(t)

    def isAnagram2(self, s, t):
        return sorted(s) == sorted(t)


if __name__ == '__main__':
    sol = Solution()
    s = "anagram"
    t = "nagaram"
    print sol.isAnagram(s, t)
    print sol.isAnagram2(s, t)

你可能感兴趣的:([LeetCode][Python]242. Valid Anagram)