首页 > 其他 > 详细

有效的字母异位词

时间:2020-05-21 16:44:35      阅读:35      评论:0      收藏:0      [点我收藏+]

链接: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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!