有一个任务是找到列表中的所有数字序列,然后将它们添加到另一个列表中。比如list中有这样一个数字序列
12222533343332
只有数字必须出现在结果列表中,就像这样 44
77
88
000
前提是重复数字必须并排
例如,所以
5122225333433325
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
。我得到 333
和 33
。我该如何改进?
最佳答案
这里的想法是存储索引j
每个序列的开头。然后,当序列在索引 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]
关于java - 在列表中找到数字序列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52337404/