Leetcode-Valid Anagram-Python
来源:互联网 发布:淘宝6s官换机是真的吗 编辑:程序博客网 时间:2024/06/01 08:43
Valid Anagram
给定两个字符串,判断其中一个字符串是否是另一个字符串的异序组合。
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = “anagram”, t = “nagaram”, return true.
s = “rat”, t = “car”, return false.
Description
tip:anagram的意思是把单词的字母顺序打乱,重新排列后变成一个新单词。
解题思路1:
将两个字符串排序后直接比较是否相同。
class Solution(object): def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ return sorted(s) == sorted(t)
解题思路2:
采用字典的方式,分别记录两个字符串中每个字符的出现次数,比较字典是否相同。
class Solution(object): def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ dict1, dict2 = {}, {} for i in s: dict1[i] = dict1.get(i, 0) + 1 for j in t: dict2[j] = dict2.get(j, 0) + 1 return dict1 == dict2
tip:
dict.get(key, default=None):对于键key返回其对应的值,或者若dict中不包含key则返回default(注意,default的默认值是None)。
阅读全文
0 0
- Leetcode-Valid Anagram-Python
- 【LEETCODE】242-Valid Anagram [Python]
- leetcode 242. Valid Anagram python
- [leetcode: Python]242.Valid Anagram
- leetcode(5),Valid Anagram(python)
- Leetcode #242 Valid Anagram
- leetcode-242-Valid Anagram
- Leetcode: Valid Anagram
- 【leetCode】Valid Anagram
- [leetcode] 242.Valid Anagram
- leetcode 242: Valid Anagram
- 【leetcode】Valid Anagram
- [leetcode] Valid Anagram
- LeetCode Valid Anagram
- 【LeetCode】242 Valid Anagram
- [LeetCode] Valid Anagram
- leetcode: Valid Anagram
- leetCode(53):Valid Anagram
- TensorFlow 使用 tf.scalar tf.summary
- POJ 3660 Cow Contest floyd传递闭包
- ScrollView起始位置不是顶部布局的解决办法
- 2017.8.28
- java中计算一段代码执行的时间
- Leetcode-Valid Anagram-Python
- vue 文件目录详解
- 【ARM-Linux开发】Linux模块机制浅析
- ACM 母函数问题模板
- Salting password密码加盐
- Java基础之--多线程
- 关于冒泡排序法的优化
- DKOM隐藏驱动
- logback 常用配置详解(二) <appender>