zoukankan      html  css  js  c++  java
  • leetcode No.242 有效的字母异位词 valid-anagram (Python3实现)

    题目描述

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

    示例 1:

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

    输入: s = "rat", t = "car"
    输出: false
    说明:
    你可以假设字符串只包含小写字母。

    题目解法

    方法一:统计词频进行比较

    class Solution:
        def isAnagram(self, s: str, t: str) -> bool:
            from collections import Counter
            maps = Counter(s)
            mapt = Counter(t)
            return maps == mapt
    

    方法二:统计字母序号

    class Solution:
        def isAnagram(self, s: str, t: str) -> bool:
            c1 = [0]*26
            c2 = [0]*26
            
            for c in s:
                pos = ord(c) - ord('a')
                c1[pos] = c1[pos] + 1
                
            for c in t:
                pos = ord(c) - ord('a')
                c2[pos] = c2[pos] + 1
                
            return c1 == c2
    

    题目拓展:

    来源:https://www.v2ex.com/t/624125
    题目要求:比较两个单词,看前一个单词能否用后一个单词中的字母拼接出来。

    def can_be_composed(a, b):
        a_count = collections.Counter(a)
        b_count = collections.Counter(b)
        return all(a_count[k] <= b_count.get(k, 0) for k in a_count)
    

    思路一致,只是词频不是用等号,用<= ,使用all确保所有条件都符合。

  • 相关阅读:
    Linux之wget命令
    Markdown语法
    Windows实时预览markdown
    Python基础教程,Python入门教程(非常详细)
    【转载】UNICODE与ASCII的区别
    Python之虚拟环境
    Linux文件系统管理
    Linux权限管理
    linux用户和用户组管理
    linux 软件安装
  • 原文地址:https://www.cnblogs.com/everfight/p/leetcode_242.html
Copyright © 2011-2022 走看看