java - 集合中的平等爪哇
问题描述
我有一个返回的方法Set<Set<String>>
。在我的测试中,我正在尝试Set
使用方法检查预期的 s 是否存在contains()
。
例如。input = "cat", "dog", "god"
output = [[cat], [dog, god]]
现在,如果我这样做output.contains(new HashSet<>(Arrays.asList("cat")))
,它会返回true
.
但如果我这样做output.contains(new HashSet<>(Arrays.asList("dog", "god")))
,它会返回false
。
根据我的理解,它应该true
在两种情况下都返回。
我在这里想念什么?
public class AnagramGroups {
public Set<Set<String>> group(Set<String> words) {
Set<Set<String>> groups = new HashSet<>();
for(String word: words) {
findAndAdd(word, groups);
}
return groups;
}
private void findAndAdd(String word, Set<Set<String>> groups) {
for(Set<String> group: groups) {
boolean found = false;
for(String str: group) {
if(isAnagram(str, word)) {
found = true;
}
break;
}
if(found) {
group.add(word);
return;
}
}
Set<String> set = new HashSet<>();
set.add(word);
groups.add(set);
}
private boolean isAnagram(String str, String word) {
Set<Character> characters = new HashSet<>();
for(char c: str.toCharArray()) {
characters.add(c);
}
for(char c: word.toCharArray()) {
if(!characters.contains(c)) {
return false;
}
characters.remove(c);
}
return characters.isEmpty();
}
public static void main(String[] args) {
Set<Set<String>> groups = new AnagramGroups()
.group(new HashSet<>(Arrays.asList("cat", "god", "dog")));
System.out.println(groups);
Set set1 = new HashSet<>(Arrays.asList("cat"));
Set set2 = new HashSet<>(Arrays.asList("god", "dog"));
System.out.println(groups.contains(set1));
System.out.println(groups.contains(set2));
groups.add(new HashSet<>(Arrays.asList("god", "dog")));
System.out.println(groups);
}
}
解决方案
问题出在你的方法中,你正在改变外部( )findAndAdd
的元素(),因此改变它的. 结果,找不到存在于 中的 a ,因为它在错误的存储桶(匹配新的)而不是添加它的存储桶(匹配原始的)中查找它。group
Set
groups
hashCode()
groups.contains(set2)
Set
groups
hashCode()
hashCode()
group
Set
您可以通过在对其进行变异之前删除from来修复您的代码groups
,然后重新添加它。
更改您的代码:
private void findAndAdd(String word, Set<Set<String>> groups) {
for(Set<String> group: groups) {
boolean found = false;
for(String str: group) {
if(isAnagram(str, word)) {
found = true;
}
break;
}
if(found) {
group.add(word);
return;
}
}
Set<String> set = new HashSet<>();
set.add(word);
groups.add(set);
}
到:
private void findAndAdd(String word, Set<Set<String>> groups) {
for(Set<String> group: groups) {
boolean found = false;
for(String str: group) {
if(isAnagram(str, word)) {
found = true;
}
break;
}
if(found) {
groups.remove(group);
group.add (word);
groups.add(group);
return;
}
}
Set<String> set = new HashSet<>();
set.add(word);
groups.add(set);
}
当我尝试您的代码并进行更改时,我true
在这两种情况下都得到了。
输出:
[[cat], [god, dog]]
true
true
[[cat], [god, dog]]
推荐阅读
- c# - 反向单词但点应该在最后
- python - 使用 Python 刷新 Tableau 仪表板
- typescript - 为 props 定义 mobx-react-lite 观察者泛型
- xslt - 如何再次转换从 XSLT 获得的 XML 输出
- android-studio - 在调试器中更改 kotlin val
- r - 在 R Studio 中,如何阻止我的 for 循环用最新的输出覆盖存储的输出?
- reactjs - 无法在新的 ZoomIndicator 处读取未定义的属性“地图”
- entity-framework - 错误:支持“NameDbContext”上下文的模型自创建数据库以来已更改
- c# - 如何从列表视图中的 DropDownList 检索值?
- python - 变分自编码器回归类型的重构损失