Saturday, May 21, 2022

Valid Anagram



import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.util.Arrays;

public class ValidAnagram {

@Test
public void test() {
String s = "anagram";
String t = "nagaram";
Assertions.assertTrue(isAnagram(s, t));
Assertions.assertTrue(isAnagramWithKey(s, t));

String a = "rat";
String b = "cat";
Assertions.assertFalse(isAnagram(a, b));
Assertions.assertFalse(isAnagramWithKey(a, b));

}

public boolean isAnagram(String s, String t) {
int[] array = new int[128];
for (char c : s.toCharArray()) {
array[c]++;
}
for (char c : t.toCharArray()) {
array[c]--;
}
for (int a : array) {
if (a != 0) {
return false;
}
}
return true;
}

public boolean isAnagramWithKey(String s, String t) {
return key(s).equals(key(t));
}

public String key(String s) {
int[] array = new int[128];
for (char c : s.toCharArray()) {
array[c]++;
}
return Arrays.toString(array);
}
}

No comments:

Post a Comment