- One string is an anagram of another if the second is simply a rearrangement of the first.
- We check to see that each character in the first string actually occurs in the second.
Python code:
def anagramSolution1(s1,s2):
s1= s1.replace(" ", "").lower()
s2= s2.replace(" ", "").lower()
#edge cases
if len(s1) != len(s2):
return False
# create a dictonary
count = {}
for letter in s1:
if letter in count:
count[letter] += 1
else:
count[letter] = 1
for letter in s2:
if letter in count:
count[letter] -= 1
else:
count[letter] = 1
for k in count:
if count[k] != 0:
return False
return True
print(anagramSolution1('abcd','dcba'))
No comments:
Post a Comment