当前位置: 首页 > news >正文

[python 刷题] 242 Valid Anagram

[python 刷题] 242 Valid Anagram

题目:

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

这里 Anagram 的定义就是可以通过重新排序获得的单词,如 cat 可以获得 act,这种,所以满足的条件有两个:

  1. 字串 A 里包含的字母和字串 B 一样多
  2. 字串 A 中出现字母的频率与字串 B 一样多

我刚开始的写法是这样的:

class Solution:def isAnagram(self, s: str, t: str) -> bool:# s being an anagram of t means:#   1. same length#   2. same # of charsif len(s) != len(t):return False# create a dict to store key val frequencychar_dict = {}for l in s:if l in char_dict:char_dict[l] = char_dict[l] + 1else:char_dict[l] = 1# find if all chars appeared in the dictfor l in t:if l not in char_dict:return Falseif char_dict[l] == 1:del char_dict[l]else:char_dict[l] = char_dict[l] - 1return True

第一个检查字符串的长度,二者不一致就可以直接返回 false

然后进入两个循环,第一个循环创建一个 dict,进行字符和频率的 mapping,第二个循环检查当前字符是否出现在 dict 中,如果没有返回 false,如果有,那么出现的频率减少

如果第二个循环走完了,就代表两个字符的出现的字符串频率一致,也就可以返回 true

写完后我参考了一下别人的写法,发现一个更优雅的答案:

class Solution:def isAnagram(self, s: str, t: str) -> bool:if len(s) != len(t):return FalsecountS, countT = {}, {}for i in range(len(s)):countS[s[i]] = 1 + countS.get(s[i], 0)countT[t[i]] = 1 + countT.get(t[i], 0)return countS == countT

我找了一下,dict 中的 get 第二个参数为默认值,即当当前值不存在于 dict 中使用的值,这样可以减少一重 if/else

比较两个 dict 这个我找了下资料, Comparing two dictionaries and checking how many (key, value) pairs are equal

中提到了 python 的文档中 Mapping Types — dict¶ 用了这个案例:

The following examples all return a dictionary equal to {"one": 1, "two": 2, "three": 3}:

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True

Providing keyword arguments as in the first example only works for keys that are valid Python identifiers. Otherwise, any valid keys can be used.

另一个 post What does the == operator actually do on a Python dictionary? 中提到,== 中有提到,== 的结果为 true 的情况 sorted(key, value) 结果完全一致,第一条回答找了一个 python 的源码实现,说内部进行递归调用判断 dict 中每个元素都是相通的,不过目前代码的 reference 消失了

总结就是,如果两个 dict 的 key 相同,每个 key 的 value 也相同,就可以用 ==

http://www.lryc.cn/news/168680.html

相关文章:

  • 算法通过村第七关-树(递归/二叉树遍历)青铜笔记|手撕递归
  • #循循渐进学51单片机#点亮你的LED#not.2
  • 基于Java+SpringBoot+Vue+uniapp点餐小程序(亮点:协同过滤算法、会员系统,购物车结算、在线聊天)
  • 深度学习-全连接神经网络-详解梯度下降从BGD到ADAM - [北邮鲁鹏]
  • 数据结构--二叉排序树
  • Python | 根据子列表中的第二个元素对列表进行排序
  • qsort函数详细讲解以及利用冒泡排序模拟实现qsort函数
  • C++QT day6
  • List与ArrayList
  • 【C++】特殊类的设计
  • 机器学习:PCA(Principal Component Analysis主成分)降维
  • linux服务器slab缓存回收方案设计
  • Apache Spark 的基本概念
  • 通讯协议介绍CoAP 协议解析
  • React 开发一个移动端项目(2)
  • 51单片机 点阵矩阵 坤坤代码
  • Android13-图片视频选择器
  • 【问题处理】GIT合并解决冲突后,导致其他人代码遗失的排查
  • H264视频压缩格式
  • 动态的中秋爱心演示送女友用python生成爱心软件文末附c++语言写法
  • macOS - 使用VLC
  • java微服务项目整合skywalking链路追踪框架
  • pandas 笔记: interpolate
  • 应用程序接口(API)安全的入门指南
  • JavaWeb概念视频笔记
  • 网络请求【小程序】
  • python 调用adb shell
  • vue3 使用 vite 构建的项目打包后无法访问
  • C语言指针详解(4)———找工作必看指针笔试题汇总
  • 03MyBatis-Plus中的常用注解