LeetCode242 Valid Anagram
Author: Stefan Su
Create time: 2022-10-31 01:15:00
Location: New York City, NY, USA
Description Easy
Given two strings s
and t
, return true if t
is an anagram of s
, and false otherwise.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1
Input: s = "anagram", t = "nagaram"
Output: true
Example 2
Input: s = "rat", t = "car"
Output: false
Constrains
1 <= s.length, t.length <= 5 * 10
4s
andt
consist of lowercase English letters.
Analysis
Use hash array to store the 26 letters in record
array. Once the letter appears in the s
, then at the position of that letter, which is also the index in the record
, adds one. Keep doing so. Go through each letter in string t
as well. But subtract each record[index of letter in t]
. After these two for loops are done, check whether there is all zero in record
, if yes, these two strings are anagram. If no, they are not.
Solution
- Hash as an array
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
record = [0] * 26
for _ in s:
record[ord(_) - ord('a')] += 1
for _ in t:
record[ord(_) - ord('a')] -= 1
for _ in record:
if _ == 0:
continue
else:
return False
return True
Hopefully, this blog can inspire you when solving LeetCode242. For any questions, please comment below.