1

文字列内のすべての一意の繰り返しを取得し、それらを長さと繰り返し頻度 (数) で並べ替える最良の方法を考えています。

私はこのコードから始めています

 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 の位置

私はあなたの助けに感謝します

4

1 に答える 1

5

まず第一に、あなたのパターンはあなたが望むものをあなたに与えません. 正規表現を次のように変更する必要があります: -

"(\\S)\\1+"

単一の文字の繰り返しを取得します。

繰り返しの場所と回数を取得するために、Map<String, List<Integer>>各繰り返しの場所を保存するために を維持できます。

forまた、内にそのループは必要ありませんwhile。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]}
于 2012-12-05T19:29:29.873 に答える