LeetCode 242. 有效的字母异位词

110 阅读1分钟

Table of Contents

一、中文版

二、英文版

三、My answer

四、解题报告


一、中文版

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

示例 1:

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

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

进阶:
如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?

来源:力扣(LeetCode)
链接:leetcode-cn.com/problems/va…
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

二、英文版

Given two strings s and t , write a function to determine if t is an anagram of s.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true
Example 2:

Input: s = "rat", t = "car"
Output: false
Note:
You may assume the string contains only lowercase alphabets.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

 

三、My answer

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False
        counter_s = collections.Counter(s)
        counter_t = collections.Counter(t)
        for key,val in counter_s.items():
            if counter_t[key] != val:
                return False
        return True

四、解题报告

数据结构:字典

算法:判断 s 和 t 中字符个数是否一致即可。一旦出现一个不一致的即返回 false.