242. Valid Anagram
Problem Statement
Given two strings s
and t
, return true
if t
is an anagram of s
, and false
otherwise.
NOTE: 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.
Examples
Example 1:
Input: s = "anagram"
, t = "nagaram"
Output: true
Example 2:
Input: s = "rat"
, t = "car"
Output: false
Constraints
s.length
,t.length
s
andt
consist of lowercase English letters.
Submissions
python
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
return sorted(s) == sorted(t)
python
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
countS, countT = {}, {}
for char in s:
countS[char] = 1 + countS.get(char, 0)
for char in t:
countT[char] = 1 + countT.get(char, 0)
return countS == countT
Explanations
Python
Submitted by @noeyislearning
class Solution:
: This is the class that contains the functioncontainsDuplicate
.def isAnagram(self, s: str, t: str) -> bool:
: This function takes two stringss
andt
as input and returns a boolean value.if len(s) != len(t): return False
: If the lengths of the two strings are not equal, returnFalse
.return sorted(s) == sorted(t)
: Sort the characters in both strings and compare them. If the sorted strings are equal, returnTrue
; otherwise, returnFalse
.
Python
Submitted by @noeyislearning