@@ -23,7 +23,9 @@ private Anagrams() {
2323 * @param t the second string
2424 * @return true if the strings are anagrams, false otherwise
2525 */
26- public static boolean approach1 (String s , String t ) {
26+ public static boolean areAnagramsBySorting (String s , String t ) {
27+ s = s .toLowerCase ().replaceAll ("[^a-z]" , "" );
28+ t = t .toLowerCase ().replaceAll ("[^a-z]" , "" );
2729 if (s .length () != t .length ()) {
2830 return false ;
2931 }
@@ -43,17 +45,18 @@ public static boolean approach1(String s, String t) {
4345 * @param t the second string
4446 * @return true if the strings are anagrams, false otherwise
4547 */
46- public static boolean approach2 (String s , String t ) {
47- if (s .length () != t .length ()) {
48- return false ;
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 ]++;
4954 }
50- int [] charCount = new int [26 ];
51- for (int i = 0 ; i < s .length (); i ++) {
52- charCount [s .charAt (i ) - 'a' ]++;
53- charCount [t .charAt (i ) - 'a' ]--;
55+ for (char ch : t .toCharArray ()) {
56+ dict [ch ]--;
5457 }
55- for (int count : charCount ) {
56- if (count != 0 ) {
58+ for (int e : dict ) {
59+ if (e != 0 ) {
5760 return false ;
5861 }
5962 }
@@ -70,7 +73,9 @@ public static boolean approach2(String s, String t) {
7073 * @param t the second string
7174 * @return true if the strings are anagrams, false otherwise
7275 */
73- public static boolean approach3 (String s , String t ) {
76+ public static boolean areAnagramsByCountingCharsSingleArray (String s , String t ) {
77+ s = s .toLowerCase ().replaceAll ("[^a-z]" , "" );
78+ t = t .toLowerCase ().replaceAll ("[^a-z]" , "" );
7479 if (s .length () != t .length ()) {
7580 return false ;
7681 }
@@ -96,7 +101,9 @@ public static boolean approach3(String s, String t) {
96101 * @param t the second string
97102 * @return true if the strings are anagrams, false otherwise
98103 */
99- public static boolean approach4 (String s , String t ) {
104+ public static boolean areAnagramsUsingHashMap (String s , String t ) {
105+ s = s .toLowerCase ().replaceAll ("[^a-z]" , "" );
106+ t = t .toLowerCase ().replaceAll ("[^a-z]" , "" );
100107 if (s .length () != t .length ()) {
101108 return false ;
102109 }
@@ -123,7 +130,9 @@ public static boolean approach4(String s, String t) {
123130 * @param t the second string
124131 * @return true if the strings are anagrams, false otherwise
125132 */
126- public static boolean approach5 (String s , String t ) {
133+ public static boolean areAnagramsBySingleFreqArray (String s , String t ) {
134+ s = s .toLowerCase ().replaceAll ("[^a-z]" , "" );
135+ t = t .toLowerCase ().replaceAll ("[^a-z]" , "" );
127136 if (s .length () != t .length ()) {
128137 return false ;
129138 }
0 commit comments