zoukankan      html  css  js  c++  java
  • 有效的字母异位词

    链接: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
  • 相关阅读:
    Iscroll滑动无效
    原生js 无缝滚动组件
    原生 js dialog弹窗组件
    html5 历史管理
    html5拖拽属性
    highcharts 数据图设置X轴间隔显示效果
    highcharts柱状图含有正负柱设置不同颜色的方法
    移动端滑动插件 swiper
    千分位添加和去掉方法
    dubbo常用类和路径
  • 原文地址:https://www.cnblogs.com/wl413911/p/12931495.html
Copyright © 2011-2022 走看看