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确保所有条件都符合。

posted @ 2019-11-29 10:52  bingo彬哥  阅读(230)  评论(0编辑  收藏  举报
本站总访问量