Leetcode-Valid Anagram-Python

来源:互联网 发布:淘宝6s官换机是真的吗 编辑:程序博客网 时间:2024/06/01 08:43

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.

Description

tip:anagram的意思是把单词的字母顺序打乱,重新排列后变成一个新单词。

解题思路1
将两个字符串排序后直接比较是否相同。

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

解题思路2
采用字典的方式,分别记录两个字符串中每个字符的出现次数,比较字典是否相同。

class Solution(object):    def isAnagram(self, s, t):        """        :type s: str        :type t: str        :rtype: bool        """        dict1, dict2 = {}, {}        for i in s:            dict1[i] = dict1.get(i, 0) + 1        for j in t:            dict2[j] = dict2.get(j, 0) + 1        return dict1 == dict2

tip:
dict.get(key, default=None):对于键key返回其对应的值,或者若dict中不包含key则返回default(注意,default的默认值是None)。

原创粉丝点击