有几种方法可以解决它。
方法 1 - 使用自定义哈希码函数
我们可以有 hashCode 函数,例如:
static int[] primes = {3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103};
static String alphabet = "abcdefghijklmnopqrstuvwxyz";
public static int hashCode(String s){
int sum = 0;
for(char c: s.toCharArray()){
sum += primes[c-97];
}
return sum;
}
生成两个字符串的哈希值,如果 hashCode 相等,则字符串是字谜词。该方法类似于Jin提到的解决方案,因为它以某种方式为字符串生成hashCode。
时间复杂度 - O(n)
方法 2 - 使用字符和整数的哈希图
将 2 个字符串视为 2 个字符数组。遍历第一个数组,将字符添加到 char 和 count 的 hashmap 中,找到字符时增加计数。同样遍历第二个数组,递减哈希图中的计数器,或者如果没有找到该字符,则它们不是字谜。最后,当map包含所有字符且计数为0时,则又有2个字符串是字谜词。
方法 3 - 使用计数数组(我最喜欢的)
boolean are_anagrams(string1, string2){
let counts = new int[26];
for each char c in lower_case(string1)
counts[(int)c]++
for each char c in lower_case(string2)
counts[(int)c]--
for each int count in counts
if count != 0
return false
return true
}