MCPcopy Create free account
hub / github.com/TheAlgorithms/Java / Anagrams

Class Anagrams

src/main/java/com/thealgorithms/strings/Anagrams.java:13–151  ·  view source on GitHub ↗

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. For example, the word anagram itself can be rearranged into nag a ram, also the word binary into brainy and the word adobe into abode. Reference from

Source from the content-addressed store, hash-verified

11 * Reference from https://en.wikipedia.org/wiki/Anagram
12 */
13public final class Anagrams {
14 private Anagrams() {
15 }
16
17 /**
18 * Checks if two strings are anagrams by sorting the characters and comparing them.
19 * Time Complexity: O(n log n)
20 * Space Complexity: O(n)
21 *
22 * @param s the first string
23 * @param t the second string
24 * @return true if the strings are anagrams, false otherwise
25 */
26 public static boolean areAnagramsBySorting(String s, String t) {
27 s = s.toLowerCase().replaceAll("[^a-z]", "");
28 t = t.toLowerCase().replaceAll("[^a-z]", "");
29 if (s.length() != t.length()) {
30 return false;
31 }
32 char[] c = s.toCharArray();
33 char[] d = t.toCharArray();
34 Arrays.sort(c);
35 Arrays.sort(d);
36 return Arrays.equals(c, d);
37 }
38
39 /**
40 * Checks if two strings are anagrams by counting the frequency of each character.
41 * Time Complexity: O(n)
42 * Space Complexity: O(1)
43 *
44 * @param s the first string
45 * @param t the second string
46 * @return true if the strings are anagrams, false otherwise
47 */
48 public static boolean areAnagramsByCountingChars(String s, String t) {
49 s = s.toLowerCase().replaceAll("[^a-z]", "");
50 t = t.toLowerCase().replaceAll("[^a-z]", "");
51 int[] dict = new int[128];
52 for (char ch : s.toCharArray()) {
53 dict[ch]++;
54 }
55 for (char ch : t.toCharArray()) {
56 dict[ch]--;
57 }
58 for (int e : dict) {
59 if (e != 0) {
60 return false;
61 }
62 }
63 return true;
64 }
65
66 /**
67 * Checks if two strings are anagrams by counting the frequency of each character
68 * using a single array.
69 * Time Complexity: O(n)
70 * Space Complexity: O(1)

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected