leetcode 字谜

242. Valid Anagram
Easy

Given two strings s and , write a function to determine if t is an anagram of s.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false

 

 

ord() 函数是 chr() 函数(对于8位的ASCII字符串)或 unichr() 函数(对于Unicode对象)的配对函数,它以一个字符(长度为1的字符串)作为参数,返回对应的 ASCII 数值,或者 Unicode 数值,如果所给的 Unicode 字符超出了你的 Python 定义范围,则会引发一个 TypeError 的异常

class Solution:
def isAnagram(self, s: str, t: str) -> bool:
s_l = len(s)
t_l = len(t)
dic = {}
for i in range(97,123):
dic[chr(i)] = [0,0]
if s_l != t_l:
return False
for i in s:
dic[i][0] += 1
for j in t:
dic[j][1] += 1
for j in t:
if dic[j][0] != dic[j][1]:
return False
return True

 

最优的方法

 

class Solution:
def isAnagram(self, s: str, t: str) -> bool:

'''
s_l = len(s)
t_l = len(t)
dic = {}
for i in range(97,123):
dic[chr(i)] = [0,0]
if s_l != t_l:
return False
for i in s:
dic[i][0] += 1
for j in t:
dic[j][1] += 1
for j in t:
if dic[j][0] != dic[j][1]:
return False'''
for i in string.ascii_lowercase:
if s.count(i) != t.count(i):
return False
return True

return True

posted on 2019-04-25 21:00  冬天里暖阳  阅读(151)  评论(0编辑  收藏  举报

导航