LeetCode 242_ 有效的字母异位词

1. 题目描述

 异位符指字母相同, 但次序不同.

2. 代码

1 class Solution:
2     def isAnagram(self, s: str, t: str) -> bool:
3         return sorted(s) == sorted(t)

思路: 利用sorted()进行排序, 然后比较运算符==直接返回结果.

3. 整理

3.1 sorted()

sort 是应用在 list 上的方法, sorted 可以对所有可迭代的对象进行排序操作.

 list 的 list.sort() 方法会修改原始的 list(返回值为None), 通常这个方法不如sorted()方便, 如果你不需要原始的 list, list.sort()方法效率会稍微高一些.

附菜鸟教程sorted函数介绍: https://www.runoob.com/python3/python3-func-sorted.html

3.2 比较运算符==

比较对象是否相等, 返回False 或者True.

另一种方法: 哈希

代码

 1 import collections
 2 
 3 class Solution:
 4     
 5     def isAnagram(self, s: str, t: str) -> bool:
 6         c1 = collections.Counter(s)
 7         c2 = collections.Counter(t)
 8         # print(c1)
 9         # print(c2)
10         if len(c1) != len(c2):
11             return False
12         for k,v in c1.items():
13             # print(c1.items())
14             if k not in c2 or v != c2[k]:    #如果k不在c2或者v不等于c2对应的值,就返回false
15                 return False
16         return True

整理:

1. collections是python内置的一个类库, 详细介绍https://www.jianshu.com/p/47f66ff4ab7b

2. 字典 items() 方法: 以列表返回可遍历的(键, 值) 元组数组.

    语法: dict.items()

1 dict = {'Name': 'Runoob', 'Age': 7}
2 print(dict.items())
1 dict_items([('Name', 'Runoob'), ('Age', 7)])

列表中每一个元素是一个元组

方括号是列表, 也就是可变的数组

圆括号括起来的, 是不可变的数组

字典{}

元组()

列表[]

遍历:

1 dict = {'Name': 'Runoob', 'Age': 7}
2 for i,j in dict.items():
3     print(i, ":	", j)
Name :   Runoob
Age :    7

将字典的 key 和 value 组成一个新的列表:

1 d={1:"a",2:"b",3:"c"}
2 result=[]
3 for k,v in d.items():
4     result.append(k)
5     result.append(v)
6 print(result)
[1, 'a', 2, 'b', 3, 'c']
原文地址:https://www.cnblogs.com/vvzhang/p/13796305.html