File tree 1 file changed +46
-0
lines changed
1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
1
+ // https://leetcode.com/problems/valid-anagram/
2
+
3
+ class Solution {
4
+
5
+ private void strToMap (String s , Map <Character , Integer > sMap ) {
6
+
7
+ for (char c : s .toCharArray ()) {
8
+
9
+ Character ch = Character .valueOf (c );
10
+
11
+ if (sMap .containsKey (ch )) {
12
+ sMap .put (c , sMap .get (ch ) + 1 );
13
+ }
14
+ else {
15
+ sMap .put (ch , 1 );
16
+ }
17
+ }
18
+ }
19
+
20
+ public boolean isAnagram (String s , String t ) {
21
+
22
+ /*
23
+ * Time Complexity: O(n) where n = max(s.length, t.length). strToMap() will iterate both strings
24
+ * and will take more time on the longest string.
25
+ *
26
+ * Space Complexity: O(n + a) where n = max(s.length, t.length) and a = the size of the largest hash map.
27
+ * E.g., if S is 26 characters long and has unique letters, then the charArray() and Map will hold 26 elements.
28
+ * If S is 26 characters long and has 1 unique letter, then the char array will hold 26 letters while the map
29
+ * has 1 element.
30
+ */
31
+
32
+ if ((s .isEmpty () && !t .isEmpty ()) || (!s .isEmpty () && t .isEmpty ())) {
33
+ return false ;
34
+ }
35
+
36
+ // Create 2 maps
37
+ Map <Character , Integer > sMap = new HashMap <>();
38
+ Map <Character , Integer > tMap = new HashMap <>();
39
+
40
+ // Store string in map
41
+ strToMap (s , sMap );
42
+ strToMap (t , tMap );
43
+
44
+ return sMap .equals (tMap );
45
+ }
46
+ }
You can’t perform that action at this time.
0 commit comments