leetcode :Valid Anagram
来源:互联网 发布:linux的家目录 编辑:程序博客网 时间:2024/06/08 09:05
ord()函数是chr()函数(对于8位的ASCII字符串)或unichr()函数(对于Unicode对象)的配对函数,它以一个字符(长度为1的字符串)作为参数,返回对应的ASCII数值,或者Unicode数值,如果所给的Unicode字符超出了你的Python定义范围,则会引发一个TypeError的异常
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.
s与t是两个字符串,看看t是不是s的打乱顺序的情况
方法一:建立26个字母的字典,然后向两个字典中依次添加字符串中有的字母,最后统计
class Solution(object): def isAnagram(self, s, t): dic1, dic2 = [0]*26, [0]*26 for item in s: dic1[ord(item)-ord('a')] += 1 #ord是返回ASCII码 for item in t: dic2[ord(item)-ord('a')] += 1 #这个循环中是先将s的循环循环结束,之后再循环t的 return dic1 == dic2
方法二: 建立两个字典,将字符串中含有的字母作为键值,最后进行比较两个字典是否相等
def isAnagram1(self, s, t): dic1, dic2 = {}, {} for item in s: dic1[item] = dic1.get(item, 0) + 1 for item in t: dic2[item] = dic2.get(item, 0) + 1 return dic1 == dic2
应该也可以使用一个字典,字母在s中则在字典中加一在t中则减一
方法三
对字符串s,t分别进行排序
class Solution(object): def isAnagram(self, s, t): return sorted(s) == sorted(t)
阅读全文
0 0
- 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
- leetcode Valid Anagram 异位体
- [leetcode 242]Valid Anagram
- leetcode Valid Anagram
- leetCode #242 Valid Anagram
- LeetCode题解:Valid Anagram
- Linux内核:中断、软中断、tasklet
- Android录屏通过udp共享到其它手机
- leetcode 674 Longest Continuous Increasing Subsequence
- ajax 配置项type和method的区别
- 在3种数据库中使用关键字作为字段名的解决方法
- leetcode :Valid Anagram
- kylin源码走读_kylinConfig
- MV*关于业务逻辑的描述
- 网站后台不能添加图片,如果是服务器权限问题,应该如何解决?方法如下
- 欢迎使用CSDN-markdown编辑器
- Maven的安装配置
- GIT相关
- bzoj 2435: [Noi2011]道路修建(DFS)
- Linux内核:工作队列