LeetCode 242. 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.

Note:
You may assume the string contains only lowercase alphabets.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

分析

有效字谜

  • 输入:两个字符串
  • 条件:无
  • 任务:判断两个字符串是否互为字谜
  • 输出:True or False

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution(object):
def isAnagram(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
def isAnagram2(self, s, t):
dic1, dic2 = [0]*26, [0]*26
for item in s:
dic1[ord(item)-ord('a')] += 1
for item in t:
dic2[ord(item)-ord('a')] += 1
return dic1 == dic2
def isAnagram3(self, s, t):
return sorted(s) == sorted(t)

点评

有效字谜的两个字符串,条件是构成字符串的每个字母出现的次数应该对应相等
可以分别用两个字典记录每个字母出现的次数,然后比较这两个字段是否相等
或者直接将两个字符串排序,比较这两个字符串是否相等