-
Notifications
You must be signed in to change notification settings - Fork 0
/
anagram.py
71 lines (51 loc) · 1.57 KB
/
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
'''
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
Constraints:
1 <= s.length, t.length <= 5 * 10^4
s and t consist of lowercase English letters.
Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
'''
import string
def isAnagram(s, t):
# Initialize 2 dicts with the alphabet as keys and 0 as values
alphabet = string.ascii_lowercase
dict1 = {x : 0 for x in alphabet}
dict2 = {x : 0 for x in alphabet}
for x in s:
dict1[x] += 1
for x in t:
dict2[x] += 1
return dict1 == dict2
def isAnagramOptimized(s, t):
if len(s) != len(t):
return False
dict = {x: 0 for x in string.ascii_lowercase}
for x in s:
dict[x] += 1
for x in t:
dict[x] -= 1
if dict[x] < 0:
return False
return True
def isAnagramOptimized2(s, t):
return sorted(s) == sorted(t)
# Some Test cases
if __name__ == "__main__":
# Examples
input = [
('anagram', 'nagaram', True),
('rat', 'car', False)
]
for idx, (s, t, expected) in enumerate(input):
print("\nExample", idx, ":")
print("Input:", s, " ", t)
print("Output:", isAnagramOptimized2(s, t))
print("Expected:", expected)