java检查字符串的所有字符是否包含相同的次数
我正在做以下问题陈述:
A string is valid if all characters of the string appear the same number of times. It is also valid if we can remove just 1 character at 1 index in the string, and the remaining characters will occur the same number of times. Given a string s, determine if it is valid. If so, return YES, otherwise return NO.
For example, if
s=abc
, it is a valid string because frequencies are{a:1,b:1,c:1}
. So iss=abcc
because we can remove onec
and have 1 of each character in the remaining string. Ifs=abccc
however, the string is not valid as we can only remove 1 occurrence ofc
. That would leave character frequencies of{a:1,b:1,c:2}
.
我想出了下面的代码,但它并没有像预期的那样工作,并且在这个输入上失败了abcdefghhgfedecba
。它正在打印“否”,但对于该输入,它应该是“是”
private static String isValid(String s) {
if (s == null || s.equals("")) {
return "NO";
}
Map<Character, Integer> frequencies = new HashMap<>();
for (char ch : s.toLowerCase().toCharArray())
frequencies.put(ch, frequencies.getOrDefault(ch, 0) + 1);
int count = 0;
// Iterating over values only
for (Integer value : frequencies.values()) {
if (value == 2) {
count++;
}
}
if (count >= 1) {
return "YES";
}
return "NO";
}
我怎么了?做这件事的最佳和有效的方法是什么
# 1 楼答案
下面的代码可以正常工作。我在这里做的是存储数组中每个字符的频率,然后将其转换为列表,因为我们需要稍后的时间点。接下来,我将列表转换为set,并从中删除了零,因为列表中的零对应于输入字符串中不存在的字符。如果在移除零后设置只有on元素,则表示所有元素的频率相同,因此返回true。如果集合有两个以上的元素,则表示无法通过在一个位置删除一个字符来使其成为有效字符串,因此返回false。现在如果集合有两个值,我们从集合中取最小值和最大值。我们可以使它有效,如果有一个字符具有一个频率,这就是第一个条件。第二个条件是,如果最大值和最小值之差为一,最大值只有一个频率,那么我们可以从最大值中删除一个字符,使其有效
# 2 楼答案
计算频率是正确的想法,尽管我不确定为什么要检查映射中的值是否为
2
。一旦我计算了这些频率,我就会创建一个具有每个频率的字符数的反向映射,然后:编辑:
为了回答评论中的问题,频率图和“频率频率”图也可以用Java 7的语法构建,尽管它可能没有那么优雅:
# 3 楼答案
爪哇8
python 3