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
  • 相关阅读:
    洛谷 P1555 尴尬的数字
    洛谷 P1318 积水面积
    9.8解题报告
    洛谷 P1464 Function
    洛谷 P1122 最大子树和
    cogs 66. [HAOI2004模拟] 数列问题
    49. 跳马问题
    洛谷 P3137 [USACO16FEB]圆形谷仓Circular Barn_Silver
    codevs 3164 质因数分解
    codeforces 482C Game with Strings
  • 原文地址:https://www.cnblogs.com/wl413911/p/12931495.html
Copyright © 2011-2022 走看看