有效的字母异位词

链接:https://leetcode-cn.com/problems/valid-anagram

给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。

示例 1:

输入: s = "anagram", t = "nagaram"
输出: true

思路1:排序

时间复杂度:O(nlogn)

python代码:

  

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

思路2:用map计数,比较两个map是否相同

时间复杂度:O(n)

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
  dic1 ,dic2 = {},{}
  for item in s:
    dic1[item] = dic1.get(item,0) +1
  for item in t:
    dic2[item] = dic2.get(item,0) +1
 
  return dic1==dic2
 
 
思考一种特殊的情况:字符串中只包含26个小写字母, 那么还可以这样写
 
  
class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
  dic1 , dic2 = [0]*26 ,[0]*26
  for c in s:
    dic1[ord(c) - ord('a')] += 1
  for c in t:
    dic2[ord(c) - ord('a') += 1
  return dic1 == dic2
原文地址:https://www.cnblogs.com/wl413911/p/12931495.html