File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Space complexity: O(2n) - 주어진 한 단어안의 각 문자가 서로 다 다를 경우 생성한 맵들의 최대 길이는 주어진 단어만큼이므로 2n
2
+ // Time complexity: O(3n) - 각 맵을 생성하고 추가로 각 아이템을 비교하는 루프가 필요하므로 3n
3
+
4
+ use std:: collections:: HashMap ;
5
+
6
+ pub fn is_anagram ( s : String , t : String ) -> bool {
7
+ // Check if the lengh of the 2 words are same.
8
+ // Otherwise return false.
9
+ let len01 = s. len ( ) ;
10
+ let len02 = t. len ( ) ;
11
+ if len01 != len02 {
12
+ return false ;
13
+ }
14
+
15
+ // Prepare and fill a new map for s
16
+ let mut s_map = HashMap :: new ( ) ;
17
+ for s_char in s. chars ( ) {
18
+ let n = s_map. get ( & s_char) . copied ( ) . unwrap_or ( 0 ) ;
19
+ s_map. insert ( s_char, n + 1 ) ;
20
+ }
21
+
22
+ // Prepare and fill a new map for t
23
+ let mut t_map = HashMap :: new ( ) ;
24
+ for t_char in t. chars ( ) {
25
+ let n = t_map. get ( & t_char) . copied ( ) . unwrap_or ( 0 ) ;
26
+ t_map. insert ( t_char, n + 1 ) ;
27
+ }
28
+
29
+ // Iterate over the map s, so compare with the map t
30
+ // to see if both have same number for the same character respectively
31
+ for ( s_char, num) in s_map. iter ( ) {
32
+ if t_map. get ( s_char) . copied ( ) . unwrap_or ( 0 ) != * num {
33
+ return false ;
34
+ }
35
+ }
36
+
37
+ true
38
+ }
39
+
40
+ #[ cfg( test) ]
41
+ mod tests {
42
+ use super :: * ;
43
+
44
+ #[ test]
45
+ fn test_good ( ) {
46
+ let result = is_anagram ( "ana" . to_owned ( ) , "aan" . to_owned ( ) ) ;
47
+ assert ! ( result) ;
48
+ }
49
+
50
+ #[ test]
51
+ fn test_bad ( ) {
52
+ let result = is_anagram ( "aaa" . to_owned ( ) , "aan" . to_owned ( ) ) ;
53
+ assert ! ( !result) ;
54
+ }
55
+ }
56
+
You can’t perform that action at this time.
0 commit comments