File tree Expand file tree Collapse file tree 1 file changed +50
-10
lines changed Expand file tree Collapse file tree 1 file changed +50
-10
lines changed Original file line number Diff line number Diff line change 1
1
from typing import List
2
2
3
3
# Time Complexity O(n log n)
4
- # - when sorting by sorted function(TimSort) for each string it takes O(nlogn)
5
- # - traversing for loop takes O(n)
4
+ # - check len first
5
+ # - make set for one of list for each values
6
+ # - if there's a duplication, then value += 1. This is a number of count.
7
+ # - fetch value using set.get() method.
8
+ # - minus 1 and check if it is less than 0 which means it's invalid. return false directly.
6
9
# Space Complexity O(n)
7
10
# - when sorting takes O(n)
8
11
9
12
class Solution :
10
13
def isAnagram (self , s : str , t : str ) -> bool :
11
- s_sorted = sorted (s )
12
- t_sorted = sorted (t )
13
14
14
- for i in range (len (s_sorted )):
15
- if s_sorted [i ] != t_sorted [i ]:
16
- return False
17
- return True
15
+ """
16
+ :type s: str
17
+ :type t: str
18
+ :rtype: bool
19
+ """
20
+ s_list = list (s )
21
+ t_list = list (t )
22
+
23
+ if len (s_list ) != len (t_list ):
24
+ return False
25
+
26
+ t_set = {}
27
+ for t_val in t_list :
28
+ cur = t_set .get (t_val , 0 )
29
+ cur += 1
30
+ t_set [t_val ] = cur
31
+
32
+
33
+ flag = True
34
+
35
+ for s_val in s_list :
36
+ if t_set .get (s_val ):
37
+ cur = t_set .get (s_val )
38
+ cur -= 1
39
+ t_set [s_val ] = cur
40
+ if cur < 0 :
41
+ flag = False
42
+ break
43
+ else :
44
+ flag = False
45
+ break
46
+
47
+ return flag
48
+
49
+ # previous logic
50
+ # s_sorted = sorted(s)
51
+ # t_sorted = sorted(t)
52
+
53
+ # for i in range(len(s_sorted)):
54
+ # if s_sorted[i] != t_sorted[i]:
55
+ # return False
56
+ # return True
57
+
18
58
19
59
if __name__ == "__main__" :
20
60
solution = Solution ()
21
61
22
- s = "nagaram "
23
- t = "anagram "
62
+ s = "a "
63
+ t = "ab "
24
64
25
65
result = solution .isAnagram (s , t )
26
66
print (result )
You can’t perform that action at this time.
0 commit comments