leetcode 242. 有效的字母异位词 valid-anagram (Python3实现)

时间:2019-11-29
本文章向大家介绍leetcode 242. 有效的字母异位词 valid-anagram (Python3实现),主要包括leetcode 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确保所有条件都符合。

原文地址:https://www.cnblogs.com/everfight/p/leetcode_242.html