【问题标题】:Is there a class in Java which keeps duplicates but not order of data?Java中是否有一个类可以保留重复但不保留数据顺序?
【发布时间】:2020-01-31 17:08:02
【问题描述】:

我正在处理字谜,所以我只关心字符串中存在的字符,而不关心它们的顺序。 我搜索了一个合适的 Collection 类但徒劳无功。

您能否建议任何可以帮助我的课程 保留重复但忽略顺序

【问题讨论】:

  • Guava Multiset?或者只是一个Map<Key, Integer>,其中Integer 存储键的出现次数?
  • 实际上,如果您想检查字谜排序集合也很有用。只要他们保留重复项。这是真正的原因“ccba”由于字谜与“cabc”相同,但由于字谜也类似于“abcc”。因此,对两者进行排序都会以两次“abcc”结束,它们是相等的!

标签: java collections anagram


【解决方案1】:

您可以使用Map<Character,Integer> 来计算String 的每个字符出现的次数。如果为两个Strings 生成的Maps 相等,您就会知道对应的Strings 是字谜。

例如(这里我使用Map<Integer,Long>而不是Map<Character,Integer>,因为这样更方便):

String one = "animal";
String two = "manila";
Map<Integer,Long> mapOne = one.chars ().boxed().collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
Map<Integer,Long> mapTwo = two.chars ().boxed().collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
System.out.println ("Is anagram? " + mapOne.equals(mapTwo));

输出:

Is anagram? true

【讨论】:

    【解决方案2】:

    您可以使用 Google guava 的HashMultiSetequals() 方法正是这样做的:

    比较指定对象与此多重集是否相等。如果给定对象也是一个 多重集并包含具有相等计数的相等元素,无论 命令。如果 object 是 大小相同,并且如果对于每个元素,两个多重集具有相同的 数。

    【讨论】:

      【解决方案3】:

      除了有序的数据结构外,还可以对数据进行动态排序。

      由于 Unicode 符号 代码点 优于 UTF-16 chars,我将使用 Unicode ints 代替:

      int[] canonical(String s) {
          return s.codePoints().sorted().toArray();
      }
      
      boolean isAnagram(String s, String t) {
          return Arrays.equals(canonical(s), canonical(t));
      }
      
      boolean isAnagram(int[] s, String t) {
          return Arrays.equals(s, canonical(t));
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-04
        • 1970-01-01
        • 2012-05-31
        • 1970-01-01
        • 2021-05-13
        • 1970-01-01
        相关资源
        最近更新 更多