[leetcode: Python]242.Valid Anagram

来源:互联网 发布:万方免费数据库查询 编辑:程序博客网 时间:2024/06/16 14:57

题目:
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?

题意:
字符串s&t,判断它俩的组成成分是不是一样的,相当于判断字符串t是否是由s打乱顺序生成的。
假定字符串只包含小写的英文字母。
思考:
如果字符串包含UNICODE,该怎么修改算法?

方法一:性能126ms
先判断两个字符串长度;把字母转换为ASC2码,排序再比较排序数组。

class Solution(object):    def isAnagram(self, s, t):        """        :type s: str        :type t: str        :rtype: bool        """        if len(s) == 0 and len(t) == 0:            return True        if len(s) == 0 or len(t) == 0:            return False        s1 = []        for i in s:            s1.append(ord(i))        s1.sort()        t1 = []        for i in t:            t1.append(ord(i))        t1.sort()        if s1 == t1:            return True        else:            return False

方法二:性能48ms

class Solution(object):    def isAnagram(self, s, t):        """        :type s: str        :type t: str        :rtype: bool        """        if len(s) != len(t):            return False        for word in set(s):            if s.count(word) != t.count(word):                return False        return True
0 0
原创粉丝点击