我的字符串列表如下所示:
List<String> parentDataList: {"this", "is", "a", "test", "string", "and", "a", "test", "other"}
List<String> child1: {"a", "test"}
List<String> child2: {"this", "string"}
List<String> child3: {"is", "a", "test"} 我希望检查父列表是否包含序列子列表,然后根据子列表获取父列表中的开始索引和结束索引。
从上面的例子:
Parent contain child1 list, and return the indexes: [2 - 3] and [6 - 7]
Parent doesn't contain child2 list because it isn't sequential.
Parent contain child3 list, and return the index: [1 - 3] 我尝试使用List.containsAll方法,但它不关心列表项的顺序,也无法从这个方法获得开始和结束索引。
我正在寻找最快的方法来做到这一点,因为我的列表有很多数据,我必须从许多输入字符串搜索。
任何帮助都将不胜感激!
更新
我需要得到所有的索引子列表都包含在父列表中。例如,父类包含两个位置的child1 :2-3和6-7。
发布于 2013-11-26 17:15:29
Collections.indexOfSubList方法将提供所需的信息。
返回指定目标列表在指定源列表中的第一个匹配项的起始位置,如果没有此类事件,则返回-1。更正式地说,返回最低索引i,以便source.subList(i,i+target.size()).equals(目标),或者-1 (如果没有这样的索引)。(返回-1如果target.size() >source.size())。
int index=Collections.indexOfSubList(parentDataList, child1);
…索引间隔将从index (包含)到index+child1.size() (排他)。当然,除非返回的索引是-1。在后一种情况下,找不到子列表。
发布于 2013-11-29 07:44:23
您可以这样修改@Alessio的代码。它也适用于你的案子。
public List<Interval> getIntervals(String[] parent, String[] child) {
List<Interval> intervals = new ArrayList<Interval>();
Interval interval = new Interval();
for (int i = 0, j = 0; i < parent.length; i++) {
if (child[j].equals(parent[i])) {
j++;
if (j == 1) {
interval.start = i;
}
if (j == child.length) {
interval.end = i;
intervals.add(interval);
interval = new Interval();
j = 0;
}
} else {
j = 0;
}
}
return intervals;
}发布于 2013-11-26 17:22:24
如果您想手动执行此操作:
public static List<Interval> getIntervals2(String[] parent, String[] child) {
List<Interval> intervals = new ArrayList<Launch.Interval>();
for (int i = 0; i < parent.length; i++) {
if (child[0].equals(parent[i])) {
Interval interval = new Interval();
interval.start = i;
intervals.add(interval);
}
}
ListIterator<Interval> iterator = intervals.listIterator();
while (iterator.hasNext()) {
Interval interval = iterator.next();
for (int j = 1, i = interval.start + 1; i < child.length; i++, j++) {
if (!child[j].equals(parent[i]))
iterator.remove();
}
if (interval.start + child.length - 1 < parent.length - 1)
interval.end = interval.start + child.length - 1;
else
iterator.remove();
}
return intervals;
}https://stackoverflow.com/questions/20223487
复制相似问题