-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path242-valid-anagram.py
30 lines (22 loc) · 1.24 KB
/
242-valid-anagram.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#242 Valid Anagram Problem Description:
#Given two strings s and t, return true if t is an anagram of s, and false if otherwise.
class Solution(object):
def isAnagram(self, s, t):
#check if the lengths of both strings are the same, if they are not then return false because they cannot be anagrams
if len(s) != len(t):
return False
#initiate two dictionaries that we will fill with the contents of both strings
countS = {}
countT = {}
#loop over the length of the string s
for i in range(len(s)):
#For each character in both strings, increment the count in the dictionaries, use the get() method to handle characters that have not been encountered and initialize their count to 0
countS[s[i]] = 1 + countS.get(s[i], 0)
countT[t[i]] = 1 + countT.get(t[i], 0)
#iterate over each chatacter in the countS dictionary
for c in countS:
#if the count of any character in s doesn't match the count in t, then return false
if countS[c] != countT.get(c, 0):
return False
#return true because the strings have identical character counts for each unique character
return True