leetcode-242 判断两个字符串是不是 Anagram ?
题目描述
假设给定两个字符串 s 和 t, 让我们写出一个方法来判断这两个字符串是否是字母异位词?
字母异位词就是,两个字符串中含有字母的个数和数量都一样,比如:
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
字符串 s 和 t 含有的字母以及字母的数量都一致,所以是 True.
Example 2:
Input: s = "rat", t = "car"
Output: false
字符串 s 中字母 "t" 在字符串 t 中并未出现,所以是 False.
解题思路
1) 可以初始化一个 hash map,键作为出现的字母,值作为对应字母出现的次数。
2)然后遍历字符串 s,将 map 中对应出现的字母个数加一。
3)然后接着遍历字符串 t, 将 map 中对应出现的字母个数减一。
4)最后判断 map 中是否所有的值都为 0 就可以了,如果不为 0 的话,一定表示 s 和 t 中拥有不同的字母。
# Question:
# Given two strings s and t , write a function to determine if t is an
# anagram of s.
# Type: string or array
# 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?
import string
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
# get all lower alphabets
lower_alphabets = string.ascii_lowercase
# we can init a hash map to represent the count of alphabets.
lower_alphabets_map = {alphabet: 0 for alphabet in lower_alphabets}
# Traverse the string "s" and plus 1 to the count of alphabet
# that appear
for index in s:
if index in lower_alphabets_map.keys():
lower_alphabets_map[index] += 1
# Then Traverse the string "t" and subtract 1 to the count of alphabet
# that appear
for index in t:
if index in lower_alphabets_map.keys():
lower_alphabets_map[index] -= 1
# if the count of all alphabets in the hash map is 0, then the string
# "s" and "t" are anagrams.
is_anagram = False
for value in lower_alphabets_map.values():
if value != 0:
return is_anagram
return True
if __name__ == '__main__':
solution = Solution()
print(solution.isAnagram('abc', 'abc'))
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了