【问题标题】:Sort repeats by frequency and length按频率和长度对重复进行排序
【发布时间】:2012-12-05 19:16:33
【问题描述】:

我正在考虑获取字符串中所有唯一重复并按长度和重复频率(数字)对它们进行排序的最佳方法

我从这段代码开始

 public static void main(String[] args)
{
  String s = "AAAABBBBAAAANNNNAAAABBBBNNNBBBBAAAA";
  Matcher m = Pattern.compile("(\\S{2,})(?=.*?\\1)").matcher(s);
  while (m.find())
  {
    for (int i = 1; i <= m.groupCount(); i++)
    {
      System.out.println(m.group(i));
    }
  }
}

并且想对有这样的输出提出一些建议:

AAAA 4 1,9,17,33 等等

其中 4=重复次数,1,9,17,33 个位置

感谢您的帮助

【问题讨论】:

  • 使用 HashMap 将 String 映射到 List
  • HashMap&lt;String, Set&lt;Integer&gt;&gt;String = 字符串 (AAAA),Set&lt;Integer&gt; 是索引 (1,9,17,33)。
  • 其实不需要Set——一个List就足够存储索引了。
  • 当前程序输出的第一件事是AAAABBBB
  • 但我的目标是多次重复,不仅一个 HashMap 仍然可以实现?

标签: java regex pattern-matching


【解决方案1】:

首先,你的模式不会给你想要的。您应该将您的正则表达式更改为:-

"(\\S)\\1+"

重复单个字符。

现在要获取重复的位置和次数,您可以维护一个Map&lt;String, List&lt;Integer&gt;&gt;,来存储每次重复的位置。

此外,您不需要在 while 中使用 for 循环。 while 循环足以遍历所有模式。

这是你修改后的代码:-

Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();

String s = "AAAABBBBAAAANNNNAAAABBBBNNNBBBBAAAA";
Matcher m = Pattern.compile("(\\S)\\1+").matcher(s);

while (m.find())
{
    String str = m.group();
    int loc = m.start();

    // Check whether the pattern is present in the map.
    // If yes, get the list, and add the location to it.
    // If not, create a new list. Add the location to it. 
    // And add new entry in map.

    if (map.containsKey(str)) {
        map.get(str).add(loc);

    } else {
        List<Integer> locList = new ArrayList<Integer>();
        locList.add(loc);
        map.put(str, locList);
    }

}
System.out.println(map);

输出:-

{AAAA=[0, 8, 16, 31], BBBB=[4, 20, 27], NNNN=[12], NNN=[24]}

【讨论】:

  • +1。但是,出于内存原因,在这种情况下,LinkedList 可能比ArrayList 更好。不过可能没关系。
  • 也许不用说,但现在频率是位置列表的长度。
  • @durron597。或者,Set 可能会更好。因为位置是独一无二的。
  • @RohitJain 不是真的,因为HashTableHashMap 的基础)有很多额外的空间可用于哈希条目。 LinkedList 将是此处的最小内存使用量。
  • @durron597.. 嗯。你确定吗。我的意思是我不确定,我是否得到你。但似乎hashing 可能是Set 的一些额外工作。在这种情况下,ArrayListLinkedList 真的无法区分。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-20
  • 2014-02-13
  • 1970-01-01
  • 2018-11-17
  • 2011-04-04
  • 2011-08-20
相关资源
最近更新 更多