Remove Letter To Equalize Frequency
You are given a 0-indexed string word, consisting of lowercase English letters. You need to select one index and remove the letter at that index from word so that the frequency of every letter present in word is equal.
Return true if it is possible to remove one letter so that the frequency of all letters in word are equal, and false otherwise.
Note:
The frequency of a letter x is the number of times it occurs in the string.
You must remove exactly one letter and cannot chose to do nothing.
Example 1:
Input: word = "abcc"
Output: true
Explanation: Select index 3 and delete it: word becomes "abc" and each character has a frequency of 1.
Example 2:
Input: word = "aazz"
Output: false
Explanation: We must delete a character, so either the frequency of "a" is 1 and the frequency of "z" is 2, or vice versa. It is impossible to make all present letters have equal frequency.
Constraints:
2 <= word.length <= 100
word consists of lowercase English letters only.
思路一: 用 26 长度的数组存储字符出现的次数,然后双层循环模拟减一的情况。也可以不用循环的方式判断,但是需要考虑的情况有点多,难怪通过率如此之低。为了代码清晰度,感觉 N 平方的复杂度是可以接受的
public boolean equalFrequency(String word) {
int[] arr = new int[26];
for (int i = 0; i < word.length(); i++) {
arr[word.charAt(i) - 'a']++;
}
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 0) continue;
int temp = arr[i];
arr[i] = arr[i] - 1;
Set<Integer> set = new HashSet<>();
for (int j = 0; j < arr.length; j++) {
if (arr[j] != 0) {
set.add(arr[j]);
}
if (set.size() > 1) break;
}
if (set.size() == 1) return true;
arr[i] = temp;
}
return false;
}
标签:arr,set,word,letter,int,2423,frequency,easy,leetcode
From: https://www.cnblogs.com/iyiluo/p/16849367.html