字符串数组公共字符统计代码异常:误输出多余字符的排查
问题分析与修复
错误根源
你的代码逻辑完全偏离了“所有元素共有字符”的判断标准:
- 当前代码是将所有字符串中字符的总出现次数累加,然后通过
总次数 >= 数组长度来判断是否为共有字符。 - 但这个逻辑不成立:比如字符
e在been(2次)、bean(1次)、bread(1次)中总共出现4次,刚好等于数组长度4,但它并没有出现在第四个字符串boat中,所以不符合“所有元素共有”的要求,却被误判加入结果。
正确逻辑
要找出所有字符串共有的字符,必须满足两个条件:
- 该字符在每一个输入字符串中都至少出现一次;
- 统计该字符在所有字符串中的总出现次数(此处按你的预期取总次数)。
修复后的代码
import java.util.HashMap; import java.util.Map; public class RepeatedChar { public static Map<Character, Integer> repeatedChars(String[] str) { Map<Character, Integer> output = new HashMap<>(); if (str == null || str.length == 0) { return output; } // 遍历第一个字符串的所有字符,逐个验证是否在所有字符串中存在 for (char c : str[0].toCharArray()) { if (output.containsKey(c)) continue; // 跳过已处理的字符 boolean existsInAll = true; int totalCount = 0; // 检查当前字符是否存在于每个字符串,并统计总出现次数 for (String s : str) { if (s.indexOf(c) == -1) { existsInAll = false; break; } // 统计当前字符串中该字符的出现次数 for (char ch : s.toCharArray()) { if (ch == c) totalCount++; } } if (existsInAll) { output.put(c, totalCount); } } return output; } public static void main(String[] args) { String[] input = {"been", "bean", "bread", "boat"}; System.out.println(RepeatedChar.repeatedChars(input)); } }
运行上述代码,输出为{b=4},完全符合预期。
内容的提问来源于stack exchange,提问作者simon
相关产品推荐
相关产品推荐

