本文详解“balanced words counter”面试题的核心难点——明确“subword”即连续子字符串(而非子序列或重排组合),并通过逻辑拆解与代码结构设计,帮助开发者准确统计所有满足“各字符出现频次完全相等”的非空连续子串数量。
该题的关键在于精准理解 “balanced subword” 的定义:
以测试用例 input = "aabbabcccb

? 关键洞察:“28”不是凭空构造的组合数,而是对全部 66 个子串逐一枚举 + 频次校验后的精确计数结果。 你无需手动列全,但需确保算法能无遗漏地遍历所有 [i, j](0 ≤ i ≤ j 0(即所有出现字符的频次一致且大于 0)。
以下是 BalancedWordsCounter 的核心实现思路(不含完整代码,聚焦逻辑):
public class BalancedWordsCounter {
public Integer count(String input) {
if (input == null) throw new RuntimeException("Input cannot be null");
if (!input.chars().allMatch(Character::isLetter))
throw new RuntimeException("Input must contain letters only");
int n = input.length();
int balancedCount = 0;
// 枚举所有连续子串 [i, j]
for (int i = 0; i < n; i++) {
int[] freq = new int[26]; // 假设仅小写英文字母
for (int j = i; j < n; j++) {
char c = input.charAt(j);
freq[c - 'a']++;
if (isBalanced(freq)) {
balancedCount++;
}
}
}
return balancedCount;
}
private boolean isBalanced(int[] freq) {
int min = Integer.MAX_VALUE, max = 0;
int nonZeroCount = 0;
for (int f : freq) {
if (f > 0) {
nonZeroCount++;
min = Math.min(min, f);
max = Math.max(max, f);
}
}
return nonZeroCount > 0 && min == max; // 非空且所有出现字符频次相等
}
}⚠️ 注意事项:
总结:破解本题的核心不是数学建模,而是回归定义、厘清“subword = contiguous substring”、并严格执行频次一致性判定。一旦理解这点,编码即水到渠成——枚举、统计、验证,三步闭环。