File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * AnagramChecker.java
3
+ * Checks whether two input strings are anagrams using a HashMap.
4
+ * Time Complexity: O(n), Space Complexity: O(n)
5
+ */
6
+
7
+ import java .util .HashMap ;
8
+
9
+ public class AnagramChecker {
10
+
11
+ public static boolean areAnagrams (String str1 , String str2 ) {
12
+ // Remove spaces and convert to lowercase
13
+ str1 = str1 .replaceAll ("\\ s" , "" ).toLowerCase ();
14
+ str2 = str2 .replaceAll ("\\ s" , "" ).toLowerCase ();
15
+
16
+ // Quick length check
17
+ if (str1 .length () != str2 .length ()) {
18
+ return false ;
19
+ }
20
+
21
+ // Count characters in first string
22
+ HashMap <Character , Integer > map = new HashMap <>();
23
+ for (char c : str1 .toCharArray ()) {
24
+ map .put (c , map .getOrDefault (c , 0 ) + 1 );
25
+ }
26
+
27
+ // Subtract character counts using second string
28
+ for (char c : str2 .toCharArray ()) {
29
+ if (!map .containsKey (c )) {
30
+ return false ;
31
+ }
32
+ map .put (c , map .get (c ) - 1 );
33
+ if (map .get (c ) == 0 ) {
34
+ map .remove (c );
35
+ }
36
+ }
37
+
38
+ return map .isEmpty ();
39
+ }
40
+
41
+ public static void main (String [] args ) {
42
+ String s1 = "Listen" ;
43
+ String s2 = "Silent" ;
44
+
45
+ if (areAnagrams (s1 , s2 )) {
46
+ System .out .println ("\" " + s1 + "\" and \" " + s2 + "\" are anagrams." );
47
+ } else {
48
+ System .out .println ("\" " + s1 + "\" and \" " + s2 + "\" are NOT anagrams." );
49
+ }
50
+ }
51
+ }
You can’t perform that action at this time.
0 commit comments