adolfmc

 

package java.util.Collections;

 

public static int indexOfSubList(List<?> source, List<?> target) {
int sourceSize = source.size();
int targetSize = target.size();
int maxCandidate = sourceSize - targetSize;

if (sourceSize < INDEXOFSUBLIST_THRESHOLD ||
(source instanceof RandomAccess&&target instanceof RandomAccess)) {
nextCand:
for (int candidate = 0; candidate <= maxCandidate; candidate++) {
for (int i=0, j=candidate; i<targetSize; i++, j++)
if (!eq(target.get(i), source.get(j)))
continue nextCand; // Element mismatch, try next cand
return candidate; // All elements of candidate matched target
}
} else { // Iterator version of above algorithm
ListIterator<?> si = source.listIterator();
nextCand:
for (int candidate = 0; candidate <= maxCandidate; candidate++) {
ListIterator<?> ti = target.listIterator();
for (int i=0; i<targetSize; i++) {
if (!eq(ti.next(), si.next())) {
// Back up source iterator to next candidate
for (int j=0; j<i; j++)
si.previous();
continue nextCand;
}
}
return candidate;
}
}
return -1; // No candidate matched the target }

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2022-01-02
  • 2022-01-27
  • 2021-06-11
  • 2021-08-08
  • 2021-05-04
  • 2021-08-30
  • 2021-09-15
猜你喜欢
  • 2022-12-23
  • 2021-06-18
  • 2021-08-31
  • 2021-11-28
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案