代码实现:
思路:
步骤一:统计各字母出现频率
步骤二:频率从高到低排序,形成频率数组
步骤三:频率数组只有如下组合符合要求:
- 1, 0...0
- n + 1, n...n (, 0)
- n...n, 1(, 0)
bool equalFrequency(char *word) {if (word == NULL || strlen(word) == 0 || strlen(word) == 1) {return true;}int hash[26] = {0};for (int i = 0; i < strlen(word); i++) {hash[word[i] - 'a']++;}// 出现频率从大到小排序for (char i = 25; i > 0; i++) {for (char j = 0; j < 25; j++) {if (hash[j] < hash[j + 1]) {char temp = hash[j];hash[j] = hash[j + 1];hash[j + 1] = temp;}}}char type = 0;// type = 0: 检查 1, 0...0// type = 1: 检查 n + 1, n...n (, 0)// type = 2: 检查 n...n, 1(, 0)for (char i = 0; i < 26; i++) {if (type == 0) {if (!hash[i + 1]) {return true;} else if (hash[i] - 1 == hash[i + 1]) {type = 1;} else {type = 2;}} else if (type == 1) {if (hash[i] != hash[0] - 1) {return false;} else if (i == 25 || hash[i + 1] == 0) {return true;}} else if (type == 2) {if (hash[i] == 1 && (i == 25 || hash[i + 1] == 0)) {return true;} else if (hash[i] != hash[0]) {return false;}}}return false; }