Daily Leetcode 242. Valid Anagram

https://leetcode.com/problems/valid-anagram/

问题描述:

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

Example 1:

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

Example 2:

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

题目分析:

输入两个字符串st,判断两个字符串是不是重排的,我们只需要判断两点,一是两个字符串的长度是否相同,二是组成两个字符串的各个字符数量是否相同。

我们可以初始化一个长度为26的数组,该数组的值均为0,遍历s,得到对应字符数量;再遍历t,减去对应字符数量。最后判断数组是否有非零元素,如果有,则不是重排。

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) != len(t):
return False

tmp = [0] * 26

for ch in s:
tmp[ord(ch) - ord('a')] +=1
for ch in t:
tmp[ord(ch) - ord('a')] -= 1

return all(count == 0 for count in tmp)