java - 找出列表中的数字序列?
问题描述
有一个任务是找到列表中的所有数字序列,然后将它们添加到另一个列表中。比如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
。我得到333
和33
。我该如何改进?
解决方案
这里的想法是存储每个序列开头的索引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]
推荐阅读
- delphi - 当我的光标悬停在 Delphi 中时,如何更改 TLabel 的颜色?
- node.js - 使用谷歌中等图像触发器时的应用程序/八位字节流问题(模糊图像)
- python - 为什么我不通过scrapy抓取数据?
- c++ - CTAD 无法在部分专业化中使用 SFINAE 推断模板参数
- asp.net - 使用 web.config 设置特定文件夹的权限
- javascript - 如何使用 JavaScript 变量的值更新虚拟 html 元素的样式属性?
- python - 一旦目标匹配,如何停止生成器?
- javascript - React.js:处理事件和函数声明与函数表达式
- javascript - 尽管用户取消操作并且没有进行 ajax 调用,但进度条仍在加载
- gulp - Gulp Watch 仅用于在线时间处理?我的意思是手表更改我需要继续打开 ssh 窗口?