首页 > 解决方案 > 找出列表中的数字序列?

问题描述

有一个任务是找到列表中的所有数字序列,然后将它们添加到另一个列表中。比如list中有这样一个数字序列

12222533343332

只有数字必须出现在这样的结果列表中44 77 88 000一个前提是重复的数字必须并排例如,所以

5 12222 5 33343332 5

5 不应落入结果列表,因为它们分别不彼此靠近(不是序列)

List<Integer> topList = new ArrayList<>();
    List<Integer> result = new ArrayList<>();
    int count = 0;
    boolean flag = true;

    while (count < topList.size()){
        while (flag) {
            for (int j = count + 1; j < topList.size(); j++) {
                if (topList.get(count).equals(topList.get(j))) {
                    result.add(topList.get(j));
                    System.out.println(result);
                    flag = false;
                }else {
                    flag = true;
                }
            }
            count++;
        }
    }

我尝试成对比较元素并将它们添加到工作表中,但它被添加到更多元素中,例如而不是22222,我得到222222. 而不是333和一个更多的序列333。我得到33333。我该如何改进?

标签: java

解决方案


这里的想法是存储每个序列开头的索引j。然后,当一个序列在 index 处中断时i,如果i-j > 1,则输出i-j该数字的实例j

static List<Integer> extractRepeats(List<Integer> in)
{
    List<Integer> result = new ArrayList<>();
    for(int i=1, j=0; i<=in.size(); i++)
    {
        if((i == in.size() || in.get(i) != in.get(i-1)) && ++j < i)
        {
            for(j--; j<i; j++) 
            {
                result.add(in.get(j));
            }
        }
    }
    return result;
}

测试:

public static void main(String[] args)
{
    String s = "12222533343332";
    List<Integer> in = new ArrayList<>();
    for(String ns : s.split("")) in.add(Integer.parseInt(ns));
    System.out.println(extractRepeats(in));     
}

输出:

[2, 2, 2, 2, 3, 3, 3, 3, 3, 3]

推荐阅读